js prop 子组件获取父组件的值
时间: 2023-09-23 22:13:34 浏览: 49
在 React 中,子组件可以通过 props 获取父组件传递的值。你可以将父组件的值作为 props 属性传递给子组件,在子组件中通过 this.props 访问这些值。
例如,假设在父组件中有一个名为 `parentValue` 的状态值,你可以将其传递给子组件 `ChildComponent`,并在子组件中获取该值。
父组件:
```javascript
import React, { Component } from 'react';
import ChildComponent from './ChildComponent';
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
parentValue: 'Hello from parent',
};
}
render() {
return (
<div>
<ChildComponent value={this.state.parentValue} />
</div>
);
}
}
export default ParentComponent;
```
子组件:
```javascript
import React, { Component } from 'react';
class ChildComponent extends Component {
render() {
return (
<div>
<p>Value from parent: {this.props.value}</p>
</div>
);
}
}
export default ChildComponent;
```
在上面的例子中,子组件 `ChildComponent` 通过 `this.props.value` 获取父组件传递的值,并在页面上显示出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)