React Select:传入额外数据以供自定义渲染使用

ReactSelect: pass in extra data to be used by custom render

我正在使用 React-Select。

目前我正在从 elasticsearch 获取数据并将其设置为状态:

var new_titles = []
body.hits.hits.forEach(function(obj){  // looping through elasticsearch
    new_titles.push({value: obj._source.title_id, label: obj._source.title_name})
})
this.setState({titleResults: new_titles})

稍后我使用 this.state.titleResults 并将其传递到我的 React-Select 组件中:

<Select autofocus optionComponent={DropdownOptions} options={this.state.titleResults} simpleValue clearable={this.state.clearable} name="selected-state"  value={this.state.selectedTitleValue} onChange={this.handleTitleChosen} searchable={this.state.searchable} />

这很好用。但现在我想在用户搜索我的 React-Select componentOptions 时传递与此标题相关的额外元数据。是这样的:

我只是传递 {value: obj._source.title_id, label: obj._source.title_name},但我想传递更多信息以供我的 DropdownOption 组件使用:

const DropdownOptions = React.createClass({
    propTypes: {
        children: React.PropTypes.node,
        className: React.PropTypes.string,
        isDisabled: React.PropTypes.bool,
        isFocused: React.PropTypes.bool,
        isSelected: React.PropTypes.bool,
        onFocus: React.PropTypes.func,
        onSelect: React.PropTypes.func,
        option: React.PropTypes.object.isRequired,
    },
    handleMouseDown (event) {
        event.preventDefault();
        event.stopPropagation();
        this.props.onSelect(this.props.option, event);
    },
    handleMouseEnter (event) {
        this.props.onFocus(this.props.option, event);
    },
    handleMouseMove (event) {
        if (this.props.isFocused) return;
        this.props.onFocus(this.props.option, event);
    },
    render () {
        return (
            <div className={this.props.className}
                onMouseDown={this.handleMouseDown}
                onMouseEnter={this.handleMouseEnter}
                onMouseMove={this.handleMouseMove}
                title={this.props.option.title}>
                <span>Testing Text</span>
                {this.props.children}
            </div>
        );
    }
});

您将如何向该组件传递更多信息?

好吧,如果我正确地查看了代码,那么看起来您可以将 optionRenderer 道具与您的 optionComponent 一起传递。

https://github.com/JedWatson/react-select/blob/master/src/Select.js#L874

它将您的选项作为参数,因此假设您可以在选项对象中传递其他字段并通过 optionRenderer 函数呈现。也许是这样的...

// ...
optionRenderer(option) {
    return (
        <div>
            {option.value} - {option.label} - {option.someOtherValue}
        </div>
    )
}
// ...
render() {
    let selectProps = {
        optionComponent: DropdownOptions,
        optionRenderer: this.optionRenderer,
        options: this.state.titleResults,
        simpleValue: true,
        clearable: this.state.clearable,
        name: 'selected-state',
        value: this.state.selectedTitleValue,
        onChange: this.handleTitleChosen,
        searchable: this.state.searchable,
        autofocus: true
    }
    return <Select {...selectProps} />
}