gpt4 book ai didi

javascript - React - TypeError : _this. setState 不是函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:58:06 24 4
gpt4 key购买 nike

我正在玩 React 并尝试将用户输入的文本保存到 state 的输入中。我在文本区域中添加了一个 onChange 属性来设置状态。

但是,当我开始输入时,我在控制台中看到错误,指出 TypeError: _this.setState is not a function

我尝试了不同的方法来修复它,但仍然没有。

const NewItemForm = props => (
<Form onSubmit={props.send_form}>
<Form.Group>
<TextArea
placeholder='Name your first item here'
name='item_msg'
onChange={e => this.setState({ item_msg: e.target.value })} />
<Form.Button primary content='Create Item' />
</Form.Group>
</Form>
)

class App extends Component {
constructor () {
super();
this.state = {
item_msg: ''
}
}

handleSubmit(e){
e.preventDefault();

console.log(this.state.item_msg);
}

render() {
return (
<div className="App">
<MainHeaderr />
<Container>
<NewItemForm send_form={this.handleSubmit.bind(this)} />
</Container>
</div>
);
}
}

export default App;

最佳答案

功能组件没有生命周期方法和... state :)

const NewItemForm = props => (
<Form onSubmit={props.send_form}>
<Form.Group>
<TextArea
placeholder='Name your first item here'
name='item_msg'
onChange={e => this.setState({ item_msg: e.target.value })} />
<Form.Button primary content='Create Item' />
</Form.Group>
</Form>
)

这行不通:

onChange={e => this.setState({ item_msg: e.target.value })} />

你需要的是传递回调:

const NewItemForm = props => (
<Form onSubmit={props.send_form}>
<Form.Group>
<TextArea
placeholder='Name your first item here'
name='item_msg'
onChange={props.onInputChange} />
<Form.Button primary content='Create Item' />
</Form.Group>
</Form>
)

class App extends Component {
constructor () {
super();
this.state = {
item_msg: ''
}

this.handleSubmit = this.handleSubmit.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}

handleSubmit(e){
e.preventDefault();
console.log(this.state.item_msg);
}
handleInputChange(e) {
this.setState({ item_msg: e.target.value })
}

render() {
return (
<div className="App">
<MainHeaderr />
<Container>
<NewItemForm send_form={this.handleSubmit} onInputChange={this.handleInputChange} />
</Container>
</div>
);
}
}

我知道你来自哪里,但是 NewItemForm 将被转译为 React Element 所以 this 将引用该元素,而不是 App成分。

React without JSX

关于javascript - React - TypeError : _this. setState 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49368464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com