【问题标题】:Why props alone are being used in called React function component?为什么在调用的 React 函数组件中只使用 props?
【发布时间】:2019-08-14 16:06:11
【问题描述】:

我在学习 React 时遇到了一个令人困惑的问题。在编写函数组件时,我到处都在使用 props。

我总是使用props.profile,它工作正常。但是在一个代码组件中,我必须编写 const profiles=props; 效果很好。

我尝试使用const profiles=props.profile;我还尝试在“卡片”功能组件中使用 return

{props.profile.avatar_url} 但他们都失败了

下面是我的代码,运行良好

const Card=(props)=>{
  const profiles=props; //This I dont understand
  return(
    <div>
      <div>
        <img src={profiles.avatar_url} width="75px" alt="profile pic"/>
      </div>
      <div>
        <div>{profiles.name}</div>
        <div>{profiles.company}</div>
      </div>
    </div>
  );
}

const CardList=(props)=>{
  return(
    <div>
      {testDataArr.map(profile=><Card {...profile}/>)}
    </div>
  );
}

谁能帮我理解为什么我不能使用const profiles=props.profile

还有哪些其他方法可以达到正确的结果?

【问题讨论】:

  • props.avatar_url 工作正常吗?然后就做const Card=(profiles)=&gt;{
  • @Federkun 你的意思是 const Card=({profile})=&gt;{ ?

标签: javascript reactjs


【解决方案1】:

你的testDataArr可能是这个,

testDataArr = [{avatar_url:"",name:"",company:""},{avatar_url:"",name:"",company:""},{avatar_url:"",name:"",company:""}]

现在当你这样做时,

{testDataArr.map(profile=><Card {...profile}/>)}

这里profile = {avatar_url:"",name:"",company:""}

当你这样做时,

<Card {...profile}/>

等价于,

<Card avatar_url="" name="" company=""/>

在子组件中,当你这样做时,

const profiles=props;

这里props = {avatar_url:"",name:"",company:""}

所以你可以访问它的值,

props.avatar_url

props.name

props.company

但是当你这样做时,

const profiles=props.profile

{avatar_url:"",name:"",company:""} 对象中不存在profile 键并且它失败了。

【讨论】:

    【解决方案2】:

    好的。这是问题所在,道具对象不包含配置文件属性,但它是配置文件属性。因为您在渲染 Card 元素(在 CardList 中)时正在传播 profile 变量,所以您基本上是在写:

    <Card avatarUrl={profile.avatarUrl} comapny={profile.comany} />
    

    相反,你应该这样做

    <Card profile={profile} />
    

    然后在您的 Card 组件中以这种方式访问​​数据

    const Card = (props) => {
      const profile = props.profile
    }
    

    甚至更简单

    const Card = ({profile}) => {
      return <div>{profile.comany}</div>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-28
      • 2016-10-19
      • 1970-01-01
      • 2020-10-13
      • 2021-06-16
      • 2021-10-28
      • 2020-04-03
      • 1970-01-01
      相关资源
      最近更新 更多