React-使用状态之外的函数设置组件状态,这是错误的吗?

cor*_*san 2 javascript ecmascript-6 reactjs react-native

在React组件之外的函数中使用setState是错误的吗?

例:

// myFunction.js
function myFunction() {
  ...
  this.setState({ ... })
}

// App.js
import myFunction from './myFunction

class App extends Component {
  constructor() {
    super()
    this.myFunction = myFunction.bind(this)
  }

  ...
}
Run Code Online (Sandbox Code Playgroud)

Col*_*rdo 5

我不确定您绑定的方式是否会真正起作用。您可以执行以下操作:

export const getName = (klass) => {
  klass.setState({ name: 'Colin'})
}
Run Code Online (Sandbox Code Playgroud)

然后

class App extends Component {
  state = {
    name: 'React'
  };

  handleClick = () => {
    getName(this);
  }

  render() {
    return (
      <div>
        <p>{this.state.name}</p>
        <button onClick={this.handleClick}>change name</button>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

这里的工作示例。