这是我尝试的。文档似乎表明 this.props.children
是由React管理的特殊属性,但在此示例中children
为未定义。我做错了什么?
class Child extends React.Component {
render() {
return React.createElement('div', {}, this.props.content);
}
someFunc() {
log("child", this.props.content);
}
}
class Parent extends React.Component {
render() {
return React.createElement('div', {ref: 'self'},
React.createElement(Child, {content: "child A"}, null),
React.createElement(Child, {content: "child B"}, null),
React.createElement(Child, {content: "child C"}, null)
);
}
componentDidMount() {
console.log("children:", this.props.children);
React.Children.forEach(this.props.children, (child) => {
log("child");
child.someFunc();
});
}
}
ReactDOM.render(<Parent />, document.getElementById("react"));
function log(...args) {
const elem = document.createElement("pre");
elem.textContent = [...args].join(" ");
document.getElementById("log").appendChild(elem);
}
<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="react"></div>
<div id="log"></div>
this.props.children
遍历它们时,发现它是未定义的。请注意,在我的实际代码中,我没有在
componentDidMount
中运行此代码,而是在鼠标单击的响应中调用此代码。
因此,我的第一次解决方法是,向所有子代传递EventEmitter,然后发出事件。可以通过props传递一个
registerYourselfWithParent
函数,但这也需要一个unregisterYourselfWithParent
。我猜两种方法都可以。
this.props.children
访问到你的组件的子元素。this.props.children
表示由父组件传递给你的子元素,而不是在render()
中创建的子元素。换句话说,渲染ReactDOM.render(<Parent><Child content="TEST"></Parent>, document.getElementById("react"));
将会记录具有内容"TEST"
的子元素。 - nem035