【发布时间】:2018-08-16 16:30:49
【问题描述】:
我正在使用 React 开发一个项目,我需要使用子组件的输入来更新父组件的 state。我对链中的每个函数都做了console.log(),发现我的父组件中的fetchText() 函数没有收到文本
这是我的父组件的样子
class AppComponent extends React.Component{
constructor(props){
super(props);
this.state = { markdownText: `` };
this.fetchText = this.fetchText.bind(this);
}
fetchText(text){
this.setState({ markdownText: text });
console.log(text);
}
render(){
return(
<div id="app-grid">
<h1>Markdown Viewer</h1>
<MarkDownComponent userInput={this.fetchText} />
<PreviewComponent />
</div>
);
}
}
我的子组件如下所示
class MarkDownComponent extends React.Component{
constructor(props){
super(props);
this.state = { text: ``};
this.getInput = this.getInput.bind(this);
this.sendInput = this.sendInput.bind(this);
}
getInput(event){
this.setState({ text: event.target.value });
this.sendInput();
}
sendInput(){
this.props.userInput = this.state.text;
//console.log(this.props.userInput);
}
render(){
return(
<div id="markdown-component">
<textarea id="editor" rows="16" onChange={this.getInput}></textarea>
</div>
);
}
}
当 console.log()ing this.props.userInput 在子组件中时,我会在键入时返回值。所以这表明该值正在进入属性,但为什么它不在父组件中更新?
【问题讨论】:
-
为什么将
this.props.userInput分配给this.state.text?
标签: reactjs