从父组件向子组件添加动态 html 属性 - React.js

2024-03-26

子组件:

export default class Button extends React.Component {
constructor(props) {
    super(props);
}
render() {
 return(
        <div className="form-group">
            <button

                // Need to add dynamic html attr here e.x: data-id

                key={index} 
                id={id} 
                className={`btn btn-default ${componentClass ? componentClass : null }`} 
                type="button"
                onClick={this.props.onClick}> 

                {text}

            </button>
        </div>
    );}}

父组件:

import Button from './Button';

Class App extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div className="s">
             <Button data-id="exampleData" />  // Need to add data-id attr to child button
            </div>
        );
    }

按钮组件,有它自己的默认属性,如上面提到的:id,className,type,onClick

父组件,将调用 Button 组件并添加一些附加属性,如 data-id、onChange。

注意:在搜索了一些想法之后,我知道我可以使用如下所示的扩展运算符:

父组件:

let dynamicAttributes = {"data-id":"someString", "data-attr":"someString", "data-url":"someString"};
    return (
        <div className="s">
         <Button dataSrc={ btnSrc } {...dynamicAttributes} />
        </div>
    );

我不知道如何将Button组件中的dynamicAttributes作为html attrib调用

期待这个问题有好的解决方案。提前致谢。

使用 Destructing 和 Babel 显示错误(意外标记),如下图所示。

注意:已经安装了preset-env和preset-react。


您可以利用rest destructuring子组件中的模式。根据documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Rest属性收集剩余的自己的可枚举属性键 尚未被挑选的destructuring图案。

当你直接将 props 分配给 DOM 元素时,你应该小心地使用剩余解构,因为从v16 onwards不对属性进行检查,并且允许在 DOM 元素上传递所有属性,因此即使不相关,属性也会传递到您可能不希望的 DOM 元素

附:确保您不想传递的所有属性 DOM 被单独解构。

示例片段

export default class Button extends React.Component {
  constructor(props) {
      super(props);
  }
  render() {
     const { onClick, dataSrc, ...rest } = this.props;
     return(
          <div className="form-group">
              <button
                  {...rest}
                  key={index} 
                  id={id} 
                  className={`btn btn-default ${componentClass ? componentClass : null }`} 
                  type="button"
                  onClick={onClick}> 

                  {text}

              </button>
          </div>
      );
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从父组件向子组件添加动态 html 属性 - React.js 的相关文章

随机推荐