React 类组件传值:使用 Props 传递数据
类组件可以通过 props 属性来传递值。父组件可以通过 props 属性将数据传递给子组件,子组件可以通过 this.props 来获取父组件传递的数据。
例如,父组件传递一个名为 name 的属性给子组件:
class ParentComponent extends React.Component {
render() {
return (
<ChildComponent name='John' />
);
}
}
class ChildComponent extends React.Component {
render() {
return (
<div>
My name is {this.props.name}.
</div>
);
}
}
在子组件中,使用 this.props.name 来获取父组件传递的 name 属性,并在渲染时显示出来。
原文地址: https://www.cveoy.top/t/topic/lXK3 著作权归作者所有。请勿转载和采集!