[英]having trouble passing a prop in React using a component
I am trying to pass a prop and generate a simple paragraph.我正在尝试传递一个道具并生成一个简单的段落。 I am following the docs but I am not sure what I am doing wrong.我正在关注文档,但我不确定我做错了什么。 I am sure the solution is utterly simple but I am just not finding it.我确信解决方案非常简单,但我只是没有找到它。 I take an input and generate a paragraph with that dog's name.我接受输入并用那只狗的名字生成一个段落。 Any advice would be greatly appreciated.任何建议将不胜感激。
import React from 'react';
import ReactDOM from 'react-dom';
class DisplayName extends React.Component{
render() {
return (
<p>
<span>{this.props.value}</span>
</p>
)
}
}
class NameForm extends React.Component {
constructor(props){
super(props);
this.state = {
value: ''
};
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event){
this.setState({
value: event.target.value
})
}
handleSubmit(event){
event.preventDefault()
return(
<DisplayName
value={this.state.value}
/>
)
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Favorite Dog Names:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type='submit' value='Submit'></input>
</form>
<div>
{this.handleSubmit}
</div>
</div>
)
}
}
ReactDOM.render(
<React.StrictMode>
<NameForm />
</React.StrictMode>,
document.getElementById('root')
);
You're using this.handleSubmit
in two different contexts: one to handle a click event, the second to render an element.您在两种不同的上下文中使用this.handleSubmit
:一种用于处理单击事件,另一种用于呈现元素。 This should be two separate functions since they are unrelated.这应该是两个独立的功能,因为它们不相关。
The code in the handleSubmit
function:句柄中的代码handleSubmit
:
handleSubmit(event){
event.preventDefault()
return(
<DisplayName
value={this.state.value}
/>
)
}
should become:应该变成:
handleSubmit(event){
event.preventDefault()
// shouldn't be returning a component
}
then, in render, this:然后,在渲染中,这个:
<div>
{this.handleSubmit}
</div>
should become:应该变成:
<div>
<DisplayName value={this.state.value} />
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.