kvy*_*vym 5 textfield reactjs material-ui
我正在使用 Reactjs 处理一个表单,该表单从父组件获取一些 defaultValues。
问题是,父组件使用 axios 帖子设置值的状态,并将这些值作为道具传递给子组件。我可以使用 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}/>
)}
}
Run Code Online (Sandbox Code Playgroud)
子组件
export default function Child(props) {
console.log(props.value); // THIS LOG PRINT THE VALUE PROPERLY
return(
<TextField defaultValue={props.value}/>
)
}
Run Code Online (Sandbox Code Playgroud)
这基本上是我的代码结构,但它不起作用。在此之后,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} />;
}
Run Code Online (Sandbox Code Playgroud)
或者您可以等到该值可用后再渲染您的组件
const { someValue } = this.state;
if (!someValue) {
return "loading the data";
}
return <Child value={someValue} />;
Run Code Online (Sandbox Code Playgroud)
这取决于具体情况,哪种解决方案会更好。但我认为您很可能希望更新输入中的值并对其进行处理,因此我会采用第一种情况。
| 归档时间: |
|
| 查看次数: |
4324 次 |
| 最近记录: |