从旧的外部 Javascript 更改 React 组件的状态?

2024-05-19

如何从旧的 jQuery soup 中更改 React 组件的状态 代码?

我有一个这样的组件:

var AComponent = React.createClass({
  getInitialState: function() {
    return { ids: [] }
  },
  render: function() {
    ...
  },
  onButtonClick: function() {
    ids.splice(…); // remove the last id
  }
});

当旧的 jQuery soup 代码中发生特殊情况时,我想 将 id 推送到AComponent.state.ids。我怎样才能做到这一点?

一个“明显”的解决方案是反模式;这里是:

var componentInstance = AComtonent({});
React.renderComponent(componentInstance, document.getElementById(...));

// Somewhere else, in the jQuery soup. Something special happens:
componentIntance.state.ids.push(1234);
componentIntance.setState(componentInstance.state);

这是一种反模式,根据这封来自 Facebook 的电子邮件 开发商 https://groups.google.com/d/msg/reactjs/pyUZBRWcHB4/4gnxlVQZF0MJ, 因为他写道componentInstance可能会被 React 破坏。


我将使组件成为无状态的。存储ids数组外部,并将其作为具有修改数组的函数的 prop 传递。请参阅 JSFiddle 上的示例:http://jsfiddle.net/ohvco4o2/5/ http://jsfiddle.net/ohvco4o2/5/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从旧的外部 Javascript 更改 React 组件的状态? 的相关文章

随机推荐