javascript - 使用 react.createElement 时如何设置 ref?

标签 javascript reactjs

我想获取对由我创建的元素表示的组件的引用,但无法使其工作。我试过这个:

            var comp = React.createElement(
                MyComp,
                {
                    props: myprops,
                    ref: "mycomp"
                }
            );

但这行不通。我如何在其上设置 ref 以便父级可以调用 this.refs.mycomp.someMethod()

最佳答案

https://facebook.github.io/react/docs/top-level-api.html#react.createelement

ReactElement createElement(
  string/ReactClass type,
  [object props],
  [children ...]
)

该函数的第二个参数是组件的可选 props 对象。除非你想将组件中的 Prop 称为 props.props,否则你可以拼写 myProps 对象:

var comp = React.createElement(MyComp, { ...myprops, ref: "mycomp" });

class MyComp extends React.Component {
  constructor(props) {
    super(props);
    this.initialValue = props.initialValue;
    this.state = { value: this.initialValue };
    this.increment = this.increment.bind(this);
    this.reset = this.reset.bind(this);
  }
  
  increment() {
    this.setState({ value: this.state.value + 1 });
  }
  
  reset() {
    this.setState({ value: this.initialValue });
  }
  
  render() {
    return (
      <div className="child">
        <h1>Counter: {this.state.value}</h1>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.reset = this.reset.bind(this);
  }
  
  reset() {
    this.refs.mycomp.reset();
  }
  
  render() {
    const myProps = { initialValue: 1 };
    const Comp = React.createElement(MyComp, { ...myProps, ref: "mycomp" });
    return (
      <div className="parent">
        {Comp}
        <button onClick={this.reset}>Reset</button> Calls this.refs.mycomp.reset
      </div>
    );
  }
}

  
ReactDOM.render(<App />, document.getElementById('app'));
.parent {
  background-color: #555;
  color: #FFF;
  padding: 10px;
}

.child {
  background-color: #888;
  padding: 10px;
}

h1 {
  margin: 0;
}
<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>

关于javascript - 使用 react.createElement 时如何设置 ref?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39735816/

相关文章:

javascript - 如何在div中显示另一个html文件

javascript - 在 React JS 中上传文件

javascript - 测试 React-Router v1.0.0 href

javascript - 无法使用选择器从Redux存储中获取值

javascript - React.js ES6 避免将 'this' 绑定(bind)到每个方法

javascript - angularjs不过滤其他页面

javascript - 如何在 anchor 的第二个元素上获取 CSS 左属性值

javascript - Rails 嵌套属性 form_for for has_many 使用 javascript 无限嵌套模型

javascript - Next JS 和 Vercel - 开发与生产

javascript - Cordova 与 Create-react-app