gpt4 book ai didi

javascript - 绑定(bind)到 React 组件的函数无法传递给子组件并反弹

转载 作者:行者123 更新时间:2023-11-30 20:43:49 24 4
gpt4 key购买 nike

我在这个上下文问题上遇到了麻烦:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class Foo extends Component {
constructor(props) {
super(props)
this.state = {
error: false
}
}

render() {
const { handleChange } = this.props;
let _handleChange = handleChange.bind(this);
return (
<div>
<input type='file' onChange={_handleChange} id='input'/>
<label htmlFor='input'> Upload </label>
{this.state.error && <span>{this.state.errorMessage}</span>}
</div>
)
}
}


class FooClosure extends Component {
handleChange = (event) => {
let self = this // this will always be FooClosure
debugger // local this context will be Foo
this.setState({ error: true, errorMessage: 'Some error happened'})
}
render() {
return (
<div>
<Foo handleChange={this.handleChange} />
</div>
)
}
}

class App extends Component {
render() {
return (
<div className="App">
<FooClosure />
</div>
);
}
}

export default App;

我正在尝试在父组件中定义的函数中设置状态,该函数在子组件中绑定(bind)。我对 Javascript 的理解意味着 this 将成为子组件,但 this.setState 始终在 FooClosure 的上下文中执行。谁能帮我理解这是为什么?

我可以通过定义 handleChange = (event, self) => ... 轻松解决这个问题,但我认为我不必那样做。

最佳答案

你应该这样写。

class Foo extends Component {
render() {
return (
<div>
<input type='file' onChange={this.props.handleChange} id='input'/>
<label htmlFor='input'> Upload </label>
{this.props.error && <span>{this.props.errorMessage}</span>}
</div>
)
}
}


class FooClosure extends Component {
constructor(props) {
super(props);
this.state = {error: false, errorMessage: ''};
}

handleChange = (event) => {
this.setState({ error: true, errorMessage: 'Some error happened'})
}

render() {
return (
<div>
<Foo handleChange={this.handleChange.bind(this)} error={this.state.error} errorMessage={this.state.errorMessage} />
</div>
)
}
}

关于javascript - 绑定(bind)到 React 组件的函数无法传递给子组件并反弹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48951827/

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