反应:通过ref?

时间:2016-09-02 13:37:55

标签: javascript reactjs

我正在试图弄清楚如何在React组件上访问“公共”方法,该组件已使用任意数量的高阶组件进行修饰。像这样:

int printIndex = 1;
for(int i = 0; i < array.Length; i++)
{
     print(print(array[printIndex].ToString());
     printIndex++;
     if(printindex >= array.Length)
          printindex = 0;
}

如果我现在在工具栏上获得class Toolbar extends React.Component { openSubMenu(menuName) { // whatever } render() { // whatever } } export default compose( connect(mapStateToProps, mapDispatchToProps), preload(), // custom higher order component which displays loading state )(Toolbar); ,则openSubmenu方法不可用,因为它隐藏在(在这种情况下为2)高阶组件下。无论如何都要在底层组件上使用任意方法吗?

2 个答案:

答案 0 :(得分:2)

参考Aren通过 虽然高阶组件的约定是将所有道具传递给包装组件,但它不可能通过引用。那是因为ref不是真正的道具式钥匙,它是由React特别处理的。如果将ref添加到其组件是HOC结果的元素,则ref引用最外层容器组件的实例,而不是包装组件。

检查https://facebook.github.io/react/docs/higher-order-components.html

答案 1 :(得分:0)

检查工作演示:JSFiddle

基于React的one-way data flow性质,组件函数总是由一些传入的props值触发:

var Toolbar = React.createClass({
  render: function() {
    console.log(this.props);
    return <div className={this.props.active ? "active" : ""}>Menu Item</div>;
  }
});

var Parent = React.createClass({
  open: function() {
    this.setState({
      subMenuActive: true
    });
  },
  render: function() {
    console.log(this.state);
    var isActive = (this.state || {})['subMenuActive'];
    return <div><Toolbar active={isActive}></Toolbar><button onClick={this.open}>Open sub menu</button></div>;
  }
});

因此,该过程应该 颠倒 ,这意味着:其他人应该使用某个组件,这将通过指定不同的props值来触发不同的行为。

如果要在组件内部触发某些特定功能(而不是在示例中更改className),则需要在componentWillReceivePropscomponentDidMount等特殊函数中编写一些代码。 React会在某个特定时刻调用函数:https://facebook.github.io/react/docs/component-specs.html