我想获得一个由我创建的元素表示的组件的引用,但是无法使它工作。我试过这个:
var comp = React.createElement(
MyComp,
{
props: myprops,
ref: "mycomp"
}
);
但这不起作用。如何设置参考,以便家长可以拨打this.refs.mycomp.someMethod()
?
答案 0 :(得分:4)
https://facebook.github.io/react/docs/top-level-api.html#react.createelement
ReactElement createElement( string/ReactClass type, [object props], [children ...] )
该函数的第二个参数是组件的可选props对象。除非您想将组件中的道具称为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'));
&#13;
.parent {
background-color: #555;
color: #FFF;
padding: 10px;
}
.child {
background-color: #888;
padding: 10px;
}
h1 {
margin: 0;
}
&#13;
<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>
&#13;
答案 1 :(得分:0)
从react v16.3开始,不建议使用this.refs。一种流行的方式是
const Comp = React.createElement(
MyComp,
{
props: myprops,
ref: ref => this.mycomp = ref
}
);