【问题标题】:Add custom attribute to JSX向 JSX 添加自定义属性
【发布时间】:2018-08-06 07:06:13
【问题描述】:

向 JSX 添加自定义属性的最佳方式是什么? Facebook 说它已经用 React v16 实现了。

是的。但如果我理解正确,我必须像my-custom-attribute="foo" 那样做。那对我不起作用。因为我需要像MyCustomAttribute="foo"这样的属性

有什么想法吗?

【问题讨论】:

  • 举一个你已经尝试过的例子会有所帮助

标签: reactjs typescript jsx typescript-typings


【解决方案1】:

执行以下操作以将您的自定义属性添加到组件中

预期的父组件:

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  render() {
     let selDynamicAttributes = {"data-attr":"someString", "MyCustomAttribute":"foo"}; // see here added custom attrib
    return (
      <div>
        <Button {...selDynamicAttributes}  /> //passed custom attributes
      </div>
    );
  }
}

预期的子组件:

 export default class Button extends React.Component {
    constructor(props) {
        super(props);
    }
    render(){
        const { ...otherAttributes } = this.props;
        return(
            <div>
                    <button 
                        {...otherAttributes}>
                            {this.props.displayText}
                    </button>
            </div>
        );      
    }
}

Working Demo

阅读更多:How to add custom html attributes in JSX

【讨论】:

    【解决方案2】:

    您指的是组件吗?在 javascript 中,你不能使用这种对流,它会给你一个错误“Uncaught SyntaxError: Unexpected token -”,我建议你使用最接近你的情况的snake_case。但我真正建议的是始终使用 camelCase。

    【讨论】:

    • 不。我需要它用于通用 Windows 应用程序。所以我必须在
      . 中添加一个名为“IsTabStop”的属性
    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多