加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 16:20:04 所属栏目:百科 来源:网络整理
导读:子组件: 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 bt
子组件:

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>
        );
    }

Button Component,拥有它自己的默认属性,如上所述:id,className,type,onClick

Parent Component,将调用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属性调用

期待一个很好的解决方案.提前致谢.

使用Destructing和Babel显示错误(意外令牌),如下图所示.

enter image description here

注意:已经安装了预置env和预置响应.

解决方法

您可以在子组件中使用rest destructuring pattern.根据 documentation

Rest properties collect the remaining own enumerable property keys
that are not already picked off by the destructuring pattern.

当你直接将道具分配给DOM元素时,你应该仔细使用rest destructing,因为从v16开始,没有对属性进行检查,所有属性都允许在DOM元素上传递,所以即使它不相关,属性将被传递给您可能不想要的DOM元素

P.S. Make sure that all properties that you don’t want to pass on to
the DOM are destructured separately.

示例代码段

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>
      );
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读