javascript - 对象函数属性中的 React 类 : Referencing class as "this",

标签 javascript reactjs methods this jsx

我终于开始使用 React 和 ES6,一切进展顺利,但我终于被难住了,需要一些指导。

我已经开始思考绑定(bind)问题了 this到引用该类的方法,但我想更深入一些。以此为例...它按预期工作:

class App extends Component {

    state = {
        myFirstState: false,
    };

    handleMyFirstState = () => {
        this.setState( { myFirstState : true } );
    };

    render() {

        return (
            <MyComponent handleMySate={ this.handleMyState } />
        );

    }

}

export default App;

随着方法数量的增加,我决定不将每个方法单独作为 props 传递,而是首先将它们分组在一个对象中,然后将对象作为一个整体作为 props 传递。就像这样...

class App extends Component {

    state = {
        myFirstState: false,
        mySecondState: false
    };

    handleMyFirstState = () => {
        this.setState( { myFirstState : true } );
    };

    handleMySecondSate = () => {
        this.setState( { mySecondState : true } );
    };



    render() {

        const handleStates = {
            first : this.handleMyFirstState,
            second : this.handleMySecondState
        }

        return (
            <MyComponent handleStates={ handleStates } />
        );

    }

}

export default App;

现在,我试图避免冗余代码,并在渲染开始之前将方法构建为一个对象,并将函数作为属性。差不多就是这样...

class App extends Component {

    state = {
        myFirstState: false,
        mySecondState: false
    };

    handleStates = {
        // Here is where 'this' does not reference the App class
        // I get results from the console log but setstate doesn't pass correctly
        first : () => { console.log("First Triggered"); this.setState( { myFirstState : true } ); },
        second : () => { console.log("Second Triggered"); this.setState( { mySecondState : true } ); }
    };

    render() {

        return (
            <MyComponent handleStates={this.handleStates} />
        );

    }

}

export default App;

// I trigger the function like this within MyComponent and I get the console log, but `this.setState` breaks.
<Button onClick={ this.props.handleState.first } >Handle First</button>

我已成功触发子组件 <MyComponent/> 的功能,使用后一个代码,但是 this不再引用该类,我不知道如何绑定(bind) thishandleStates因为它不是一个函数。

这是不可能的还是有其他方法来处理我想要实现的目标?

提前谢谢您!

额外

如果我移动handleStates进入render()它工作得很好...怎么可能呢?

class App extends Component {

    state = {
        myFirstState: false,
        mySecondState: false
    };

    render() {

       const handleStates = {
            first : () => { this.setState( { myFirstState : true } ); },
            second : () => { this.setState( { mySecondState : true } ); }
        };

        return (
            <MyComponent handleStates={this.handleStates} />
        );

    }

}

export default App;

最佳答案

首先,在第二个示例中,您将 this.handleStates 作为 prop handleStates 的值传递,但它是未定义的。您将 handleStates 构建为局部变量,因此您希望您的 props 引用该局部变量:

<MyComponent handleStates={handleStates} />

对于您的第三个(最后一个)示例,您的问题更加简单:您将 handleStates 定义为 this 上的一个属性,该属性被分配了一个对象,该对象本身具有两个属性, firstsecond,每个都有一个函数作为它们的值。

当您最终将 this.handleStates 传递给 MyComponent 时,您传递的是一个对象,而不是一个函数。如果您想从 MyComponent 调用 firstsecond 之一,您可以这样做:

this.props.handleStates.first()

它具有更新App中状态的预期结果。

对于它的值(value),有一个更常见的模式:只需传递一个更新函数作为 prop,根据它的作用命名:

class Sandwich extends React.Component {
  this.state = {
    bread: "",
    meat: "",
    veggie: "",
  }

  updateSandwich = (component, selection) => {
    this.setState({ [component]: selection })
  }

  render() {
    return(<IngredientSelector updateSandwich={this.updateSandwich} />)
  }
}

class IngredientSelector extends React.Component {
  return(){
    <button value="Rye" onClick={() => this.updateSandwich("bread", "rye")} />
    <button value="Wheat" onClick={() => this.updateSandwich("bread", "wheat")} />
    <button value="Ham" onClick={() => this.updateSandwich("meat", "ham")} />
    <button value="Turkey" onClick={() => this.updateSandwich("meat", "turkey")} />
  }
}

关于javascript - 对象函数属性中的 React 类 : Referencing class as "this",,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52176086/

相关文章:

javascript - Angular-vs-repeat - 使用 col-md 类时无法滚动到末尾

javascript - React中如何正确实现嵌套动态Form

python - Python 方法内定义的数据帧和变量的存储

java - 数组中包含开头和结尾元音的最长字符串

java - 具有相同签名的两种方法,为什么有效

javascript - 多维数组显示

javascript - async.forEachOfSeries 完成其任务后如何调用函数

javascript - React JS中的Exif定向图像

html - Flex 表 CSS 截断问题

javascript - "click image to display its id"及其陷阱