【问题标题】:How do I pass all other attributes in props - ReactJS如何在道具中传递所有其他属性 - ReactJS
【发布时间】:2022-01-02 17:13:44
【问题描述】:
const Label = (props) => {
  return <label className={"card-label"} {...props.attributes}>{props.children}</label>;
};

如果我尝试访问其他函数中的属性。我遇到错误,无法继续

<Label attributes={style:{margin:"10px"}}>Select Tip %</Label>

有人知道答案吗?如何使用 props 传递任何组件的所有其他属性?

【问题讨论】:

  • 通常,当您看到错误时,值得在问题中包含错误消息。
  • @DBS - 我忘了添加错误信息。下次我一定会添加错误信息。

标签: reactjs react-component


【解决方案1】:

我猜你对将 props 传递给 Label 组件的语法有疑问。试试这个

const Label = (props) => {
    return <label className={"card-label"} {...props.attributes}>{props.children}</label>;
  };

  return <Label attributes={{style:{margin:"50px"}}}>Select Tip %</Label>;

【讨论】:

  • 感谢上面的代码。我发现了错误。
  • @SambenJerald 但是你为什么接受另一个答案(顺便说一句,这是错误的)。
【解决方案2】:

你应该把你的属性值作为一个对象放入属性道具中:

return <Label className={"card-label"} attributes={{style:{}}}>Select Tip %</Label>;

一种更易读的方式是直接从 props 中提取属性:

const Label = ({ attributes, children }) => {
  return <label className={"card-label"} {...attributes}>{children}</label>;
};

【讨论】:

  • 我如何将所有其他属性(例如样式、htmlfor)作为功能组件的单个道具传递
  • 这是做什么的:&lt;label attributes={props.attributes} /&gt;?
  • 应该是 我把标签弄错了标签
猜你喜欢
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 2020-06-13
  • 1970-01-01
  • 2018-02-19
相关资源
最近更新 更多