我编写了一个包装器组件,该组件可以在此基于已接受答案的基础上被重复使用。但是,如果您只需要传递一个字符串,则只需添加一个数据属性,然后从e.target.dataset中读取它即可(就像其他一些建议一样)。默认情况下,我的包装器将绑定到作为函数的任何prop,并且以“ on”开头,并在所有其他事件参数之后自动将数据prop返回给调用者。尽管我尚未对其性能进行测试,但它将为您提供避免自己创建类的机会,并且可以像这样使用它:
const DataButton = withData('button')
const DataInput = withData('input');
或用于组件和功能
const DataInput = withData(SomeComponent);
或者如果您愿意
const DataButton = withData(<button/>)
声明在您的容器外(在您的进口附近)
这是容器中的用法:
import withData from './withData';
const DataInput = withData('input');
export default class Container extends Component {
state = {
data: [
// ...
]
}
handleItemChange = (e, data) => {
// here the data is available
// ....
}
render () {
return (
<div>
{
this.state.data.map((item, index) => (
<div key={index}>
<DataInput data={item} onChange={this.handleItemChange} value={item.value}/>
</div>
))
}
</div>
);
}
}
这是包装器代码'withData.js:
import React, { Component } from 'react';
const defaultOptions = {
events: undefined,
}
export default (Target, options) => {
Target = React.isValidElement(Target) ? Target.type : Target;
options = { ...defaultOptions, ...options }
class WithData extends Component {
constructor(props, context){
super(props, context);
this.handlers = getHandlers(options.events, this);
}
render() {
const { data, children, ...props } = this.props;
return <Target {...props} {...this.handlers} >{children}</Target>;
}
static displayName = `withData(${Target.displayName || Target.name || 'Component'})`
}
return WithData;
}
function getHandlers(events, thisContext) {
if(!events)
events = Object.keys(thisContext.props).filter(prop => prop.startsWith('on') && typeof thisContext.props[prop] === 'function')
else if (typeof events === 'string')
events = [events];
return events.reduce((result, eventType) => {
result[eventType] = (...args) => thisContext.props[eventType](...args, thisContext.props.data);
return result;
}, {});
}