因此,您确实需要将键<option>
作为props传递给,但是由于<select>
是本机字段并在内部处理更改,因此很难将键值取回。让我们一次一个问题开始,将 prop 传递到 option 可以像这样包装 option 组件并使用index
prop 作为新的 key prop 一样简单。
const CustomOption = ({ value, children, index }) => (
<option key={index} value={value}>{value}</option>
);
另请注意,我们在上面创建了一个自定义组件包装器,以将index
prop 应用于<option />
自身,因为 react 不喜欢 dom 元素上的未知 props。
现在,如果我们可以处理选项内的选定事件,我们就可以完成,但我们不能那样做。所以我们还需要进行自定义选择:
class CustomSelect extends React.Component {
static propTypes = {
value: PropTypes.object,
onChange: PropTypes.func,
}
handleChanged = (e) => {
const newValue = e.target.value;
let newKey;
// iterate through our children searching for the <CustomOption /> that was just selected
React.children.forEach(this.children, (c) => {
if (c.props && c.props.index && c.props.value === newValue) {
newKey = c.props.key;
}
});
this.props.onChange(e, newKey);
}
render() {
return (
<select value={this.props.value} onChange={this.handleChanged}>
{this.props.children}
</select>
);
}
}
它有两个propsvalue
, 和onChange
。请注意,我们拦截更改事件以找到索引(键),并将其作为第二个参数传递给父级。这不是很好,但我想不出另一种简单的方法来做到这一点,同时仍然使用本机<select>
元素。
请注意,您需要替换对这些新类的使用<select>
和<optoin>
使用,并在选项上分配index
props和key
props。