Reactjs 如何从父组件更新子组件中的输入字段 从“React”导入React; 从“./Child”导入子项; 类父类扩展了React.Component{ 建造师(道具){ 超级(道具); 此.state={ 名字:“ } this.handleChange=this.handleChange.bind(this); this.handleSubmit=this.handleSubmit.bind(this); } componentDidMount(){ 让fn=JSON.parse(localStorage.getItem(“fir”); if((localStorage.getItem(“fir”)!==未定义)和&(localStorage.getItem(“fir”)!==null)){ 这是我的国家({ 名字:fn }) } } 手变(e){ 这是我的国家({ [e.target.name]:[e.target.value] }) } handleSubmit(){ setItem(“fir”,JSON.stringify(this.state.firstName)); 警报(“已提交”); console.log(this.state.firstName) } render(){ 返回(
母公司 {this.state.firstName} ) } } 导出默认父对象; 二,Reactjs 如何从父组件更新子组件中的输入字段 从“React”导入React; 从“./Child”导入子项; 类父类扩展了React.Component{ 建造师(道具){ 超级(道具); 此.state={ 名字:“ } this.handleChange=this.handleChange.bind(this); this.handleSubmit=this.handleSubmit.bind(this); } componentDidMount(){ 让fn=JSON.parse(localStorage.getItem(“fir”); if((localStorage.getItem(“fir”)!==未定义)和&(localStorage.getItem(“fir”)!==null)){ 这是我的国家({ 名字:fn }) } } 手变(e){ 这是我的国家({ [e.target.name]:[e.target.value] }) } handleSubmit(){ setItem(“fir”,JSON.stringify(this.state.firstName)); 警报(“已提交”); console.log(this.state.firstName) } render(){ 返回(,reactjs,Reactjs,母公司 {this.state.firstName} ) } } 导出默认父对象; 二, 从“React”导入React; 子类扩展了React.Component{ 建造师(道具){ 超级(道具); 此.state={ 名字:props.firstName }; } render(){ 返回( 孩子 提交 ); } } 导出默认子对象; 这里我想更新子组件中的一个输入字段,但我被卡住了。有人能帮我更新一下吗。在child中更改下一行 import React from "react"; c
从“React”导入React;
子类扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
名字:props.firstName
};
}
render(){
返回(
孩子
提交
);
}
}
导出默认子对象;
这里我想更新子组件中的一个输入字段,但我被卡住了。有人能帮我更新一下吗。在child中更改下一行
import React from "react";
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
firstName: props.firstName
};
}
render() {
return (
<div>
<p> Child</p>
<input
type="text"
name="firstName"
value={this.state.firstName}
onChange={this.props.handleChange}
/>
<button onClick={this.props.handleSubmit}> submit</button>
</div>
);
}
}
export default Child;
到
因为firstname是作为道具传递给子组件的请更改child中的下一行
import React from "react";
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
firstName: props.firstName
};
}
render() {
return (
<div>
<p> Child</p>
<input
type="text"
name="firstName"
value={this.state.firstName}
onChange={this.props.handleChange}
/>
<button onClick={this.props.handleSubmit}> submit</button>
</div>
);
}
}
export default Child;
到
因为firstname是作为道具传递给子组件的您需要传递需要更新的值has
props
,然后在子组件中输入的值中使用该道具。我可以看到您已经传递了名字有一个道具
,您只需将状态
更改为道具
value={this.props.firstName}
您需要传递需要更新的值hasprops
,然后在子组件中输入的值中使用该props。我可以看到您已经传递了名字有一个道具
,您只需将状态
更改为道具
value={this.props.firstName}
<input
type="text"
name="firstName"
value={this.props.firstName}
onChange={this.props.handleChange}
/>