react 父子组件之间相互传值
From: https://blog.csdn.net/luzhaopan/article/details/85003362
1、定義父組件
??? import React, { PureComponent } from 'react';
??? ?
??? export default class Father extends PureComponent {
???? ?
????? render(){
??? ?
??????? return(
????????? <div>
??????????? <p>父組件</p>
?????????? ?
????????? </div>
??????? )
????? }
??? }
2、定義子組件
??? import React, { PureComponent } from 'react';
??? ?
??? export default class Children extends PureComponent {
???? ?
????? render(){
??? ?
??????? return(
????????? <div>
??????????? <p>子組件</p>
?????????? ?
????????? </div>
??????? )
????? }
??? }
3、父組件向子組件傳值
??? import React, { PureComponent } from 'react';
??? // 引入子組件
??? import Children from '@/components/Children';
??? ?
??? ?
??? export default class Father extends PureComponent {
???? ?
????? render(){
??? ?
??????? // 傳給子組件 的數據
??????? const data= {
??????? ?
????????? lt: '520',
??????? };
??? ?
??????? return(
????????? <div>
??????????? <p>父組件</p>
??? ?
???????????? <Children? data={ data } />
?????????? ?
????????? </div>
??????? )
????? }
??? }
子組件獲取父組件傳過來的值
??? import React, { PureComponent } from 'react';
??? ?
??? export default class Children extends PureComponent {
??? ?
???? constructor(props) {
??????? super(props);
??????? this.state = {
?????? ?
????? }
???? ?
????? render(){
??? ?
??????? return(
????????? <div>
??????????? <p>子組件</p>
??????????? // 獲取父組件的值
??????????? <p>{ this.props.data.lt }</p>
?????????? ?
????????? </div>
??????? )
????? }
??? }
?4、子組件向父組件傳值
??? import React, { PureComponent } from 'react';
??? ?
??? export default class Children extends PureComponent {
??? ?
??? ?
??? // 選中對應節點,選出符合條件的值
????? onSelect = () => {
??????? // 向父組件傳值
??????? const lzp= {
????????? name: lut,
????????? code: '1314',
??????? ?
??????? };
??????? this.props.handleData(lzp);
????? };
???? ?
????? render(){
??? ?
??????? return(
????????? <div>
??????????? <p>子組件</p>
??????????? <Button onClick={this.onSelect}> 向父組件傳值 </Button>
?????????? ?
????????? </div>
??????? )
????? }
??? }
??? import React, { PureComponent } from 'react';
??? // 引入子組件
??? import Children from '@/components/Children';
??? ?
??? ?
??? export default class Father extends PureComponent {
??? ?
??? handleData = (a) => {
??????? // 獲取子組件傳來的值a
??????? console.log(a);? // lzp= {name: lut,code: '1314'}
??? ?
????? };
???? ?
????? render(){
??? ?
??????? return(
????????? <div>
??????????? <p>父組件</p>
??? ?
???????????? <Children? handleData={this.handleData} />
?????????? ?
????????? </div>
??????? )
????? }
??? }
?
總結
以上是生活随笔為你收集整理的react 父子组件之间相互传值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android--Activity四种启
- 下一篇: yum安装openoffice