【问题标题】:TextField default value from parent not rendering on child来自父级的 TextField 默认值未在子级上呈现
【发布时间】:2019-12-26 20:46:15
【问题描述】:

我正在使用 Reactjs 处理从父组件获取一些 defaultValues 的表单。

问题是,父组件使用 axios post 设置值的状态,并将这些值作为 props 传递给子组件。我可以使用 console.log 在子组件上打印这些值,但是如果我尝试将这些值放在 TextFields 上的 defaultValues 上,我得到一个空表单,表单上不会呈现任何值。

父组件:

export default class Parent extends Component {
   constructor(props){
      super(props);
      this.state={
         somevalue: '',
      }
   }

   componentDidMount(){
      this.getData();
   }

   getData = async () => {
      await api.post('/getValue')
      .then((res) => {
         this.setState({
            someValue: res.data;
         })
      }).catch((err) => {
         console.log("Error: ", err);
      })
   }

   render(){
      return(
         <Child value={this.state.someValue}/>
      )}
}

子组件

export default function Child(props) {
   console.log(props.value); // THIS LOG PRINT THE VALUE PROPERLY
   return(
      <TextField defaultValue={props.value}/>
   )
}

这基本上是我的代码结构,但它不起作用。此后 TextField 仍然为空。

【问题讨论】:

    标签: reactjs material-ui textfield


    【解决方案1】:

    属性defaultValue 仅用于初始渲染。如果您检查您的代码,您会看到在 console.log 输出值之前,它将首先输出 undefined。您可以通过将defaultValue 更改为value 将其更改为受控组件。这样会显示值,但您需要为值的更改添加 onChange 处理程序。

    function Child(props) {
        // Using the value prop your value will display, but you will also have to pass an onChange handler to update the state in the parent
        return <TextField value={props.value} />;
    }
    

    或者你可以等到值可用后再渲染你的组件

    const { someValue } = this.state;
    if (!someValue) {
      return "loading the data";
    }
    return <Child value={someValue} />;
    

    这取决于具体情况,哪种解决方案会更好。但我认为您可能希望更新输入中的值并对其进行处理,所以我会选择第一种情况。

    【讨论】:

    • 感谢您的回答先生 :D 这就是诀窍!只需使用“if (!someValue){}”,defaultValue 就可以根据需要工作。
    • 看到您对答案的编辑,第二个解决方案对我来说效果更好,因为我的一些加载元素。我直接在子组件中处理这些值,并使用 axios 将它们发送回我的服务器。另外,我没有使用 TextField 值,而是使用 defaultValue 并根据需要工作。再次感谢您。
    猜你喜欢
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多