【问题标题】:What is the difference between this.state.function and this.function in ReactJSReactJS 中 this.state.function 和 this.function 有什么区别
【发布时间】:2018-07-20 23:55:18
【问题描述】:

我正在学习 React 中状态的概念。我试图了解使用 this.handleChange 和 this.state.handleChange 之间的区别。

如果有人可以向我解释两者之间的确切区别以及为什么 this.state.handleChange 不起作用,我将不胜感激?

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: ''
    }
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(event) {
    this.setState({
      inputValue: event.target.value
    });
  }
  render() {
    return (
       <div>
        < GetInput input={this.state.inputValue} handleChange={this.handleChange} />
        { /* this.handleChanges, and this.state.handleChanges */ }
         < RenderInput input={this.state.inputValue} />
       </div>
    );
  }
};

class GetInput extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h3>Get Input:</h3>
        <input
          value={this.props.input}
          onChange={this.props.handleChange}/>
      </div>
    );
  }
};

class RenderInput extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h3>Input Render:</h3>
        <p>{this.props.input}</p>
      </div>
    );
  }
};

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    只要在您的州添加handleChange,您就可以在技术上调用this.state.handleChange

    但这并没有什么意义,因为你不想让 React 跟踪它,而且它可能不会改变(除非你正在做一些 clever 技巧)。

      constructor(props) {
        super(props);
        this.state = {
          handleChange: e => {
            e.preventDefault();
            console.log("this.state.handleChange");
          }
        };
      }
    

    通常会在类中声明一个成员函数。

      handleChange = e => {
        e.preventDefault();
        console.log("this.handleChange");
      };
    

    这是完整的工作代码
    (工作演示可在 CodeSandBox 获得)。

    import React from "react";
    import ReactDOM from "react-dom";
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          handleChange: e => {
            e.preventDefault();
            console.log("this.state.handleChange");
          }
        };
      }
    
      handleChange = e => {
        e.preventDefault();
        console.log("this.handleChange");
      };
    
      render() {
        return (
          <div className="App">
            <h1>Hello CodeSandbox</h1>
            <button onClick={this.handleChange}>this.handleChange</button>
            <button onClick={this.state.handleChange}>
              this.state.handleChange
            </button>
          </div>
        );
      }
    }
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    

    【讨论】:

    • 是否有任何情况下最好使用 this.state.handleChanges 代替?
    • 我想不出任何真实世界的用例。但是可以inject 一个函数并用一个道具state = { handleChange: this.prop.handleChange } 覆盖状态方法。但是您仍然永远不会将该道具保存为状态,而只是将注入的方法称为this.prop.handleChange。你可以从实例化类中传递handleChange,比如App,比如render() { return &lt;MyApp handleChange={this.handleChange} },其中this.handleChangeApp中声明
    • @Sung 我已经看到使用 Context API 的这种情况。你创建了一个上下文提供者,它有自己的状态和私有方法,但是你通过将它们绑定到状态来公开它们,然后将它们作为一个整体传递给消费者。
    • @Chris。谢谢老哥?
    • 这是很有价值的东西@SungKim
    【解决方案2】:

    当您说this.state.something 时,这意味着该类的状态字段中有某些内容。当您说this.someFunction 时,这意味着课程本身中有东西。 this 这里指的是我们的班级。

    class App extends React.Component {
      state = {
        something: "Something",
      }
      
      someFunction = () => console.log(this.state.something);
      
      render() {
        return (
          <div>
            <button onClick={this.someFunction}>Click</button>
          </div>
        );
      }
    }
    
    ReactDOM.render(
      <App />,
      document.getElementById("app")
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="app"></div>

    因此,您不能使用this.state.handleChange,因为该州没有handleChange。它是一个属于类的函数。这就是我们使用this.handleChange 的原因。

    【讨论】:

      【解决方案3】:

      你可以在状态中存储一个函数

      constructor(super){
      super(props)
       this.state = {
        generateANumber: () => this.setState({ number: Math.floor(Math.random() * 100) }),
        number: 0
       }
      }
      

      如果你想在你的渲染方法中调用它

      render() {
       return <p> {this.state.number} <button onClick={() => this.state.generateANumber()} Press Me To Generate A New Number </button> </p> 
      }
      

      这是在状态中存储函数的概念。 this.function 仅表示该函数属于该类,因此您可以使用 this 关键字来使用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-30
        • 2021-09-11
        • 2015-07-06
        • 2021-10-13
        • 2016-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多