React - TypeError:_this.setState 不是函数

use*_*621 5 javascript reactjs

我正在使用 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;
Run Code Online (Sandbox Code Playgroud)

Tom*_*zyk 4

函数式组件没有生命周期方法并且...... 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>
)
Run Code Online (Sandbox Code Playgroud)

这是行不通的:

onChange={e => this.setState({ item_msg: e.target.value })} />
Run Code Online (Sandbox Code Playgroud)

您需要的是传递回调:

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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道你来自哪里,但NewItemForm会被转换为 React Element,因此this将引用该元素,而不是App组件。

没有 JSX 的 React