我的组件在其他render()中使用,如
return (<MyElem>Some text here</MyElem>)
如何在组件的类中访问“Some here here”字符串?
答案 0 :(得分:3)
您使用children
property。 E.g:
const Foo = props => {
console.log(props.children);
return (
<div>{props.children}</div>
);
};
ReactDOM.render(
<Foo>Hi There</Foo>,
document.getElementById("react")
);
<div id="react"></div>
<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>
它使用无状态功能组件(SFC),但Component
子类是相同的:
class Foo extends React.Component {
render() {
console.log(this.props.children);
return (
<div>{this.props.children}</div>
);
}
};
ReactDOM.render(
<Foo>Hi There</Foo>,
document.getElementById("react")
);
<div id="react"></div>
<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>
答案 1 :(得分:1)
为To MyElem添加引用:
<MyElem ref="elem">My text here<MyElem>
然后你可以在其他地方引用你的元素:
this.refs.elem