React:使用rest spread operator将道具传递给深层嵌套的子项

时间:2017-10-25 07:26:24

标签: reactjs

我正在试图找出一种干净的方式将道具传递给深层嵌套的孩子。但我收到错误Expected an assignment or function call and instead saw an expression。我很确定它是简单而愚蠢的东西,但似乎无法弄明白。这是我的代码:

class App2 extends React.Component {
  state= {
    prop1: 1,
    prop2: 2,
    prop3: 3
  }

  render () {
    return <ParentComponent {...this.state} />
  }
}



const ParentComponent = (props) => {
   <div>
     <h1>Parent Component</h1>
     <ChildComponent {...props} />
   </div>
};

const ChildComponent = ({prop1, ...rest}) =>{
  <div>
    <h1>Child Component with prop1={prop1}</h1>
    <GrandChildComponent {...rest} />
  </div>
};

const GrandChildComponent = ({prop2, prop3})=> {
  <div>
    <h1>Grand Child Component with prop2={prop2} and prop3={prop3}</h1>
  </div>
};

1 个答案:

答案 0 :(得分:1)

好的,明白了。使用{}而不是() :)

class App2 extends React.Component {
  state= {
    prop1: 1,
    prop2: 2,
    prop3: 3
  }

  render () {
    return <ParentComponent {...this.state} />
  }
}



const ParentComponent = (props) => (
   <div>
     <h1>Parent Component</h1>
     <ChildComponent {...props} />
   </div>
);

const ChildComponent = ({prop1, ...rest}) =>(
  <div>
    <h1>Child Component with prop1={prop1}</h1>
    <GrandChildComponent {...rest} />
  </div>
);

const GrandChildComponent = ({prop2, prop3})=> (
  <div>
    <h1>Grand Child Component with prop2={prop2} and prop3={prop3}</h1>
  </div>
);