对于我的生活,我不知道为什么我的反应应用程序不起作用。我的输入状态在onSubmit之后呈现。但我的价值并没有在我的输入栏中消失。我的名单上没有任何内容呈现。在将我的组件分解为较小的块之后,我只遇到了这个问题,当它是1个整个组件时我没有问题。
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
input: '',
items: []
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({
input: e.target.value
})
}
handleSubmit(e) {
e.preventDefault();
this.setState({
input: '',
items: [...this.state.items,this.state.input]
})
console.log(this.state.input)
}
render() {
return (
<div>
<Form handleChange={this.handleChange} handleSubmit={this.handleSubmit}
value={this.state.input}/>
<List items={this.state.items}/>
</div>
)
}
}
class Form extends React.Component {
constructor(props){
super(props)
}
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<input onChange={this.props.handleChange} value={this.props.input}/>
<button>Submit</button>
</form>
)
}
}
class List extends React.Component {
render() {
return (
<ul>
{
this.props.items.map((item,index) => {
<li key={index}>{item}</li>
})
}
</ul>
)
}
}
“没有消失”的问题是因为:
<input onChange={this.props.handleChange} value={this.props.input}/>
没有任何input
道具,它是value
。看到:
value={this.state.input}
所以它应该是:
<input onChange={this.props.handleChange} value={this.props.value}/>
上市问题是因为:
{
this.props.items.map((item,index) => {
<li key={index}>{item}</li>
})
}
在这里,您正在使用箭头功能和正文块。如果使用body块,则必须使用return
语句。
{
this.props.items.map( ( item, index ) => {
return ( <li key={index}>{item}</li> );
} )
}
或者您可以像这样使用它:
{
this.props.items.map( ( item, index ) =>
<li key={index}>{item}</li> )
}