来自父项的 TextField 默认值未在子项上呈现
TextField default value from parent not rendering on child
我正在使用 Reactjs 开发一个表单,它从父组件获取一些默认值。
问题是,父组件使用 axios post 设置值的状态,并将这些值作为道具传递给子组件。我可以使用 console.log 在子组件上打印这些值,但是如果我尝试将这些值放在 TextFields 上的 defaultValues 上,我会得到一个空表单,none 的值将呈现在表单上。
父组件:
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 仍然是空的。
属性 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} />;
这取决于具体情况,哪种解决方案会更好。但我认为您可能想要更新输入中的值并对其进行处理,所以我会选择第一种情况。
我正在使用 Reactjs 开发一个表单,它从父组件获取一些默认值。
问题是,父组件使用 axios post 设置值的状态,并将这些值作为道具传递给子组件。我可以使用 console.log 在子组件上打印这些值,但是如果我尝试将这些值放在 TextFields 上的 defaultValues 上,我会得到一个空表单,none 的值将呈现在表单上。
父组件:
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 仍然是空的。
属性 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} />;
这取决于具体情况,哪种解决方案会更好。但我认为您可能想要更新输入中的值并对其进行处理,所以我会选择第一种情况。