import React from 'react';
import Child from './Child';
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {
firstName: ""
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount(){
let fn = JSON.parse(localStorage.getItem("fir"));
if((localStorage.getItem("fir")!==undefined) && (localStorage.getItem("fir")!==null)){
this.setState({
firstName: fn
})
}
}
handleChange(e){
this.setState({
[e.target.name] :[e.target.value]
})
}
handleSubmit(){
localStorage.setItem("fir", JSON.stringify(this.state.firstName));
alert('submitted');
console.log(this.state.firstName)
}
render(){
return(
<div>
<p> Parent</p>
<Child
firstName={this.state.firstName}
handleChange={this.handleChange}
handleSubmit={this.handleSubmit}
/>
{this.state.firstName}
</div>
)
}
}
export default Parent;
2。
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;
在这里我想更新Child组件中的输入字段,但是我陷入了困境。任何人都可以帮助更新它。
答案 0 :(得分:0)
更改子级的以下行
value={this.state.firstName}
到
value={this.props.firstName}
因为名字作为道具传递给子组件
答案 1 :(得分:0)
您需要传递需要更新的值为props
的值,然后在子组件的输入value
中使用该道具。我可以看到您已经通过名字并带有一个prop
,您只是将state
更改为props
<input
type="text"
name="firstName"
value={this.props.firstName}
onChange={this.props.handleChange}
/>