如何将多个元素传递到React组件中

时间:2019-06-04 18:07:05

标签: reactjs components

它仅将第一个元素(element1)传递到render函数,而其他元素不起作用?我真的不明白这应该如何工作。

class ContactCard extends React.Component {

    render(){
        return <h1> Name: {this.props.name}  
        Mobile Phone: {this.props.num}  
        Work Phone: {this.props.work}</h1>
    }
}

const element1 = <ContactCard name="Mary" />;
const element2 = <ContactCard num="9176030350" />;
const element3 = <ContactCard work="2176012130" />;

ReactDOM.render(
    element1, 
     document.getElementById('root')
)

2 个答案:

答案 0 :(得分:0)

我添加了一些代码和注释来帮助您理解。问题是您用3个道具创建了3个元素,而不是1个道具。

element被赋予了name属性,但没有提供numwork属性。结果,仅呈现名称。 element2element3存在类似的问题。我们可以通过为所有属性提供一个元素(element4)来解决此问题。

class ContactCard extends React.Component {

    render(){
        return <h1> Name: {this.props.name}  
        Mobile Phone: {this.props.num}  
        Work Phone: {this.props.work}</h1>
    }
}

// these all only receive one prop
const element1 = <ContactCard name="Mary" />;
const element2 = <ContactCard num="9176030350" />;
const element3 = <ContactCard work="2176012130" />;
// all three elements above can be removed and element4 will still work

// this will receive all three
const element4 = <ContactCard name="Mary" num="9176030350" work="2176012130" />;

ReactDOM.render(
    // render element4 because it has all the props
    element4, 
    document.getElementById('root')
)

如果要呈现所有已创建的元素,则需要创建一个包含所有元素的父元素,并将该父元素传递给ReactDOM.render。这是一个示例:

const parentWithChildren = (
  <div>
    <ContactCard name="Mary" num="9176030350" work="2176012130" />
    <ContactCard name="Mary" num="9176030350" work="2176012130" />
  <div>
)

ReactDom.render(
  parentWithChildren,
  document.getElementById('root')
)

答案 1 :(得分:0)

要传递多个变量,您需要传递所有道具(例如属性)。

在下面的示例中,您可以看到<ContactCard name="Mary" num="9176030350" work="2176012130" />

import React from 'react';
import ReactDOM from 'react-dom';

class ContactCard extends React.Component {

    render(){
        return (<h1> Name: {this.props.name}  
        Mobile Phone: {this.props.num}  
        Work Phone: {this.props.work} </h1>)
    }
}
const element = <ContactCard name="Mary" num="9176030350" work="2176012130" />

ReactDOM.render( element , document.getElementById('root'));