简体   繁体   English

React,如何将道具从父组件发送到子组件? (在渲染 function 之外使用这些道具)

[英]React, How to send props from parent component to child component? (to use those props outside render function )

I want to send props from my parent component to child component.我想将道具从我的父组件发送到子组件。 this is the way i have used In parent component state-->这是我在父组件状态中使用的方式-->

chartArray:[
        {
            id:0,
            chart:'LineChart',
            device:1,
            sensor:1,

        },
        {
            id:1,
            chart:'LineChart',
            device:2,
            sensor:4,
        },]

In parent component render method --> I user Chart component and send those props在父组件渲染方法中->我使用图表组件并发送这些道具

                            {
                            chartArray.map((obj,index)=>{

                                return(
                                    <Grid item xs={12} md={12} key={index}
                                    className={classes.mainGrid} 
                                    style={{paddingBottom:30}}
                                     >


                                    <div>
                                        <div  >
                                            <div>
                                            <Typography
                                            variant={"h5"}
                                            >
                                                Device Id: {obj.device}

                                                <IconButton style={{float:'right'}}
                                                onClick={this.handleDeleteChart.bind(this,index)}
                                                >
                                                    <DeleteIcon fontSize="small" />
                                                </IconButton>
                                            </Typography>
                                            </div>

                                        </div>

                                        <div>
                                        <Typography variant={"subtitle1"}>
                                            Sensor: Temperature
                                        </Typography>

                                        </div>
                                    </div>


                                        <Paper elevation={3} 
                                        style={{
                                            overflowX: 'scroll',

                                        }}
                                        >
                                            **<Chart
                                            chartType={obj.chart} 
                                            sensorId={obj.sensor}
                                            deviceId={obj.device}
                                            />**

                                        </Paper>
                                    </Grid>

                                )



                            }

                        )}

In child component-->在子组件中-->

export default class Chart extends Component {导出默认 class 图表扩展组件 {

constructor(props){
    super(props);

    this.state={
        id:0,
        chart:props.chartType,
        device:props.deviceId,
        sensor:props.sensorId,
    }
}

async componentDidMount(){

    const response2 = await fetch(`/api/SensorData/${this.state.device}/${this.state.sensor}`)
    const bodySensors = await response2.json()

    const labels1=[]
    const data1=[]

    bodySensors.map((chartdata)=>{
        return(
            labels1.push(chartdata.date),
            data1.push(chartdata.value)
        )

    })

    this.setState({

        dataLineChart:{
            labels:[...labels1],
            datasets:[
                {
                fill:false,
                label:'Temperature',
                data:[...data1],
                backgroundColor:'rgba(210, 77, 87, 1)',
                borderColor:'rgba(137, 196, 244, 1)',
                pointBorderWidth:1,
                pointHoverRadius:10,
                pointHoverBackgroundColor:'rgba(210, 77, 87, 1)',
                pointHoverBorderColor:'rgba(137, 196, 244, 1)',
                pointHoverBorderWidth:2,
                pointRadius:2,
                // how much closer to pop up point
                pointHitRadius:10

                // steppedLine:true
            }
        ]

        }

    })


}



render() { 
    const{chartType}=this.props
    const {dataLineChart} = this.state        

    if (chartType==='BarChart')
        return (
            <BarChart />
        )
    else if (chartType==='LineChart')
        return (
            <LineChart ccData={dataLineChart}/>
        )
    else if (chartType==='PieChart')
        return (
            <PieChart/>
        )
}

} }

when i use this way to use those props outside render function.当我使用这种方式在渲染 function 之外使用这些道具时。 It works.有用。 When I add objects to parent component state--> chartArray it also works.当我将对象添加到父组件状态时-> chartArray 它也可以工作。 But when ever i delete something from that chartArray it does not send props to child component?但是,当我从该 chartArray 中删除某些内容时,它不会向子组件发送道具吗? I'm really confused here.我在这里真的很困惑。 please help.请帮忙。 Thank you谢谢

Please follow this example.请按照这个例子。

Parent Component父组件

import React, {Component, useEffect, useState} from 'react';
import PChild from "./PChild";

export class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {items: []};
    }

    componentDidMount() {
        let json = [];
        json.push({track: { id:1, name: 'Black Sabbath, from the album Black Sabbath (1970)'}});
        json.push({track: { id:2, name: 'Blackfield, from the album Blackfield (2004)'}});
        json.push({track: { id:3, name: 'Bo Diddley, from the album Bo Diddley (1958)'}});
        json.push({track: { id:4, name: 'Damn Yankees, from the album Damn Yankees (1990)'}});
        this.setState({items: json});
    }

    render() {
        return (
            <div>
                <PChild items={this.state.items} name="Khabir"/>
            </div>
        );
    }
}

Child Component子组件

import React, {useEffect, useState} from 'react';

// Parent to Child communication
export class PChild extends React.Component {

    componentDidUpdate() {
        console.log(this.props.items);
        console.log(this.props.name);
    }

    render() {
        return (
            <div>
                {this.props.items.map((item, i) => {
                    return <li key={item.track.id}>
                        {(`Item ${i+1} - ${item.track.name}`)}
                    </li>
                })}
            </div>
        );
    }
}

Because the Child doesn't get re-rendered every time the Parent Props change what you need to change is in the Child Component instead of componentDidMount use componentDidUpdate .因为每次父道具更改时不会重新渲染子对象,所以您需要更改的是子组件而不是componentDidMount使用componentDidUpdate Inside it you have to check with simple if statement the passed props value.在其中,您必须使用简单的 if 语句检查传递的 props 值。 Something in the sense:某种意义上的东西:

    componentDidUpdate(prevProps) {
    if(prevProps.chartType !== this.props.chartType||prevProps.sensorId !== 
    this.props.sensorId||prevProps.deviceId !== this.props.deviceId) { ...... your code}

} }

Of course, that is assuming everything else is working smoothly.当然,这是假设其他一切工作顺利。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将道具从父组件渲染到子组件? - How to render props from parent component to child? 如何在单个组件中渲染多个道具,然后将这些道具传递给 React 中的子组件 - How do i render multiple props in a single component and then pass those props to a child component in React 如何在本机反应中将道具从父组件传递到子组件? - How to pass props from parent component to child component in react native? React:从父级传递给子级时未定义的道具 Function 组件 - React: Props undefined when passed from Parent to Child Function Component 反应:将 2 个道具从子组件传回同一 function 中的父组件 - React: Pass 2 props back to the parent component in the same function from the child 如何在React中将props从父组件(函数)传递到子组件(CLASS) - How to pass props from parent component(function) to child component(CLASS) in React 如何使用反应原生中的道具使用从大父组件到子组件的方法? - How to use a method from grand Parent component to child component using props in react native? 如何使用 onClick 事件将 props 从子组件传递到父组件 React Hooks - How to use onClick event to pass the props from child component to parent component React Hooks 从组件外的 function 传递道具反应 - Passing props from function outside of component react React Typescript 如何发送道具并在子组件中使用它 - React Typescript how send props and use it in child component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM