在React中将对象传递给组件

问题描述

我对生活的反应方面还很陌生,遇到了一个我的语法有点烦人的问题,我可以在一点帮助下完成。

前提很简单:

我正在尝试将对象作为道具传递给组件。

父元素:-试图将状态传递给汇总组件

class Dash_overview extends React.Component{
    constructor(props){
        super(props)

        this.state = {
            companies: {
                title: 'companies on record',value: null,messurement: 'Companies'
            },earning: {
                title: 'total earning',messurement: 'mill'
            }
        }
    }
    render(){
        return (
            <div className="overview-container">
                <div className="totals">
                    <Totals values={this.state.companies}/>
                    <Totals values={this.state.earning}/>
                </div>
            </div>
        )
    }
}

子组件-将使用传递给它的值

class Totals extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            
        }
    }
    render(){
        return (
            <div className="totals_comp">
                <h3>{companies.title}</h3>
                <h3>{companies.value}</h3>
                <h3>{companies.messurement}</h3>
            </div>
        )
    }
}

-

我可能犯了一个愚蠢的错误,但是我尝试了几种不同的尝试,但均未成功,因此真的很有价值有人指出我要去哪里。 :)

预先感谢, 沃利

解决方法

您可以将状态值传播到子组件的props中,对象键将是组件内使用的prop名称。

<Totals {...this.state.companies}/>
<Totals {...this.state.earning}/>

或显式传递prop值

const { messurement,title,value } = this.state.companies;

...

<Totals
  messurement={messurement}
  title={title}
  value={value}
/>
<Totals
  messurement={messurement}
  title={title}
  value={value}
/>

然后在子级中通过道具访问

<div className="totals_comp">
  <h3>{this.props.title}</h3>
  <h3>{this.props.value}</h3>
  <h3>{this.props.messurement}</h3>
</div>

问题

values={this.state.companies}获取状态对象的值,并将其分配给名为values的prop,但是在子组件中您根本没有引用它。例如props.values.title

,

由于您要传递{title:'记录中的公司',value:null,messsurement:'Companies'}作为价值支持,因此您应该使用其他组件的价值。如果您想使用公司名称,请执行以下操作:

<div className="overview-container">
        <div className="totals">
            <Totals companies={this.state.companies}/>
            <Totals companies={this.state.earning}/>
        </div>
    </div>

,然后对“总计”组件执行此操作:

const {companies}=this.props
render(){
  return (
    <div className="totals_comp">
        <h3>{companies.title}</h3>
        <h3>{companies.value}</h3>
        <h3>{companies.messurement}</h3>
    </div>
 )}
,

尝试一下。

const { title,value,messurement }  = this.props.values;
    
    render(){
        return (
            <div className="totals_comp">
                <h3>{title}</h3>
                <h3>{value}</h3>
                <h3>{messurement}</h3>
            </div>
        )
    }