子组件: 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
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显示错误(意外令牌),如下图所示.
注意:已经安装了预置env和预置响应.
您可以在子组件中使用rest destructuring pattern.根据documentation
Rest
properties collect the remaining own enumerable property keys
that are not already picked off by thedestructuring
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> ); } }