首先通过父组件给这个子组件传递一个事件,然后子组件通过参数传过来(传到父组件)
通过props来传递事件的引用,并通过回调的方式实现的,其实就是子组件调用父组件的方法,把数据以形参的方式传出来
父组件
class App extends Component {
constructor(props) {
super(props)
this.state = {
text : "我",
editable : false
}
}
render() {
let {text,editable} = this.state
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">React子组件向父组件传递数据</h1>
</
<EditableCell
value={text}
editable= {editable}
onChange={value => this.handleChange(value)}
></EditableCell>
<button onClick={ e => this.edit()}>修改</
<h2>{text}</h2>
</div>
);
}
edit() {
this.setState({editable: true})
}
handleChange(value) {
console.log("llllllllllllllll", value)
this.setState({text:value})
}
}
子组件
//通过传参来判断是否为可编辑状态
class EditableCell extends Component {
constructor(props) {
super(props);
}
render() {
let {editable , value ,onChange} = this.props;
return (
<div>
{
this.props.editable ?
<input type="text" value={value} onChange={e => onChange(e.target.value)} style={{width:'96%',height:'38px',marginTop:'12px'}}/> :
value
}
</div>
);
}
}