<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
/*
This component is supposed to render the text the user types to the screen. However it is missing some code and is not working correctly. Add to the code below so the component prints what the user types to the screen.
*/
function InputComponent(props) {
return (
<div>
<label>
Type some text
</label>
<input onChange={props.onInput}/>
</div>
);
}
class ParentComponent extends React.Component {
onInput(event) {
this.setState({
data: event.target.value
});
}
render() {
return (
<div>
You typed: {this.state.data}
<InputComponent onInput={this.onInput}/>
</div>
);
}
}
ReactDOM.render(
<ParentComponent/>,
document.getElementById('root')
);
</script>
</body>
</html>
评论是问题所在。所以问题是
此组件应该将用户键入的文本呈现给屏幕。但是它缺少一些代码并且无法正常工作。添加到下面的代码,以便组件打印用户键入屏幕的内容。
我真的很感谢你的帮助。感谢
答案 0 :(得分:1)
问题是您没有绑定传递给子组件的方法。这意味着方法中的“this”不是指您所需的父组件。 所以你应该写:
<InputComponent onInput={this.onInput.bind(this)}/>
或者在构造函数中绑定它。
编辑: 问题发生的原因是你试图使用你从未声明的this.state.data。在ParentComponent中,首先你需要编写构造函数,如下所示:
constructor(props) {
super(props)
this.state = {
data: ''
}
this.onInput = this.onInput.bind(this) // as you are binding the method here, remove it from the props you are passing to the child component.
}