2

Is there a way to call the methods that a React component defines internally?

I understand generally we want to be passing values around declaratively with props/data etc. However I am using some component libraries that have internal useful methods.

eg

var field = <AutoComplete/>;
field.setValue("ready");  // doesn't work

eg this method https://github.com/callemall/material-ui/blob/master/src/auto-complete.jsx#L244-L248

in material-ui AutoComplete component.

4

1 回答 1

4

您不能使用虚拟 dom 来执行此操作,因为虚拟 dom 只是对要创建的组件的描述(实际组件实例只会在渲染时创建或更新)。

但是你可以在使用refs渲染后访问你的 react 组件中的组件实例:

var Test = React.createClass({
  getInitialState: function(){
    return {value:0};
  },
  setValue: function(value){
    this.setState({value:value});
  },
  render: function() {
    return <div>Value {this.state.value}</div>;
  }
});

var App = React.createClass({
  render: function() {
    return <div>
      <Test ref="test"/>
      <button onClick={()=>this.refs.test.setValue(1)}>1</button>
      <button onClick={()=>this.refs.test.setValue(2)}>2</button>
      <button onClick={()=>this.refs.test.setValue(3)}>3</button>
    </div>;
  }
});

var mountNode = document.getElementById('app');

ReactDOM.render(<App name="John" />, mountNode);

jsbin 上面的代码:http://jsbin.com/kitehujaje/1/edit?js, output

于 2015-12-21T01:57:20.640 回答