【问题标题】:React Pass Array Through PropsReact 通过 Props 传递数组
【发布时间】:2020-03-01 10:07:28
【问题描述】:

我有一个想要传递给孙子组件的数组。

class App extends Component {
 constructor(props) {
  super(props);
    ...
  }

  componentDidMount() {
   array = ['a', 'b', 'c'];
  }

  render() {
   return (
    <Child arrayData={this.props.arrayData} />  ???
   )}

我知道我必须首先通过道具将数据传递给孩子(然后从那里传递给孙子),但是我该如何格式化呢?孩子是如何收到道具的?

【问题讨论】:

标签: reactjs


【解决方案1】:

这是一个将数组中的值从父级传递给孙级的示例。注意称呼是如何在父道具中声明和分配的,并通过孩子传播给孙子。

这个例子可以很容易地修改为传递整个数组而不是其中的单个值。

  render() {
    return (
      <div>
        <h1>Passing props through the component tree...</h1>
        <Parent greeting={salutations[0]}/>        
      </div>
    );
  }
}

const Parent = (props) => {
  return (
    <div>
      <h2>Parent</h2>
      <Child greeting={props.greeting} />
    </div>
  );
};

const Child = (props) => {
  return (
    <div>
      <h3>Child</h3>
      <Grandchild greeting={props.greeting} />
    </div>
  );
};

let salutations = ["hey", "what's up", "hello"]
const Grandchild = (props) => <h4>Grandchild - {props.greeting}</h4>;

ReactDOM.render(<App />, document.getElementById('app'));

【讨论】:

  • 这看起来不错。这是钩子符号吗?我不熟悉它。
  • 这些只是组件。他们没什么特别的。如果答案对您有用,请为解决方案投票。
【解决方案2】:

你好

亲,你可以试试这个代码

import ClientImg1 from "../../assets/static/img/client/client_img_1.png";
import ClientImg2 from "../../assets/static/img/client/client_img_2.png";

const themes = {ClientImg1, ClientImg2};

render() {
   return (
    <Child arrayData1={themes.ClientImg1} arrayData2={themes.ClientImg2}/> 
   )
}

<Child arrayData1={themes.ClientImg1} arrayData2={themes.ClientImg2}/>

组件或功能页面

你可以用这个来调用他们 如果函数

function ClientSingleItem({arrayData1,arrayData2}) {
    return (
       <img src={arrayData1} alt="ClientImg" />
       <img src={arrayData2} alt="ClientImg" />
       .....
    )
}

【讨论】:

    猜你喜欢
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 2017-04-28
    • 2019-03-10
    • 2021-12-26
    • 2021-10-20
    • 2019-07-26
    相关资源
    最近更新 更多