预期:
结果:
Codepen:https://codepen.io/r11na/pen/qNKpQX
class App extends React.Component {
textBoxChange(e) {
this.props.text = e.target.value;
};
sendMessage(e) {
console.log("Send message:" + this.props.text);
};
render() {
return (
<div>
<h3>Your Message: {this.props.text.toUpperCase()}</h3>
<MessageBox textBoxChange={this.textBoxChange} sendMessage={this.sendMessage} text={this.props.text}/>
</div>
);
};
};
const MessageBox = (props) => {
return (
<div className="row column">
<textarea onChange={props.textBoxChange} value={props.text}></textarea>
<button onClick={props.sendMessage} className="button">Send</button>
<br/>
</div>
);
};
答案 0 :(得分:1)
我将props
替换为state
,添加了bind(this)
方法并进行了少量更改:
class App extends React.Component {
constructor(props) {
super(props);
this.state = { text: this.props.text };
}
textBoxChange(e) {
this.setState({ text: e.target.value });
};
sendMessage(e) {
console.log("Send message:" + this.state.text);
};
render() {
return (
<div>
<h3>Your Message: {this.state.text.toUpperCase()}</h3>
<MessageBox
textBoxChange={this.textBoxChange.bind(this)}
sendMessage={this.sendMessage.bind(this)}
text={this.state.text}
/>
</div>
);
};
};
const MessageBox = (props) => {
return (
<div className="row column">
<textarea onChange={props.textBoxChange.bind(this)} value={props.text}></textarea>
<button onClick={props.sendMessage.bind(this)} className="button">Send</button>
<br/>
</div>
);
};