简体   繁体   English

反应: Map Function 内的儿童道具

[英]React: Child Prop inside Map Function

Parent component initialized like so:父组件初始化如下:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      children: [
        {name: "Julien Lennon"},
        {name: "Sean Lennon"}
      ]
    }
  }
  render() {
    return <div class="parent">Parent, called {this.props.name}
        {this.state.children.map((child, index) => {
          return (
            <Child name="{child.name}" />
          );
        })}
    </div>;
  }
}

Now, in the child I just want to access the name prop:现在,在孩子中,我只想访问 name 道具:

class Child extends React.Component {
  render() {
    return <div class="child">Child named {this.props.name}</div>;
  }
}

But its outputing the name as a literal: Child named {child.name}但是它将名称输出为文字: Child named {child.name}

fiddle: https://jsfiddle.net/89k1zcdp/6/小提琴: https://jsfiddle.net/89k1zcdp/6/

Do this rather而是这样做

<Child name={child.name} />

You just need to remove the quotes around {child.name} in your Parent component's render function.您只需要在父组件的渲染 function 中删除 {child.name} 周围的引号。 Like this:像这样:

<Child name={child.name} />

Explanation: In React, the HTML-like code is actually React's own templating language called JSX.解释:在 React 中,类似 HTML 的代码实际上是 React 自己的模板语言,称为 JSX。 In JSX, you can indicate that a section of code is meant to be interpreted as JavaScript by wrapping it in brackets: {}.在 JSX 中,您可以通过将一段代码括在括号中来指示将其解释为 JavaScript:{}。 But since "{child.name}" is wrapped in those double quotes it turns the brackets and everything they contain into a string.但是由于"{child.name}"包含在这些双引号中,它会将括号及其包含的所有内容转换为字符串。 Removing the quotes like so {child.name} will reference the name property of the child object like you would expect JS to do.{child.name}这样删除引号将引用子 object 的 name 属性,就像您期望 JS 做的那样。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM