【发布时间】:2018-09-11 12:19:11
【问题描述】:
我收到此警告:
Warning: CreatableSelect: `ref` is not a prop. Trying to access it will result in `undefined` being returned.
我以 documentation says 的预期方式使用 ref,几乎从文档中复制粘贴(除了它用于组件,而不是基本 DOM 节点)。
但仍然反应认为我很傻,不知道 ref 是保留的。 我如何告诉 react 我正在使用 ref 作为回调 ref 而不是用于其他错误目的?
代码运行良好,唯一的问题是控制台出错。
class SearchableSelect extends Component {
constructor(props) {
super(props);
this.selector = null;
this.setSelectorRef = element => {
this.selector = element;
};
}
handleBlur() {
const { inputValue } = this.selector;
this.selector.createNewOption(inputValue);
}
render() {
const { formatMessage } = this.props.intl;
const placeholder = this.props.placeholder ? formatMessage({ id: this.props.placeholder }) : '';
return (
<Creatable
value={this.props.value}
placeholder={placeholder}
options={this.props.options}
arrowRenderer={null}
onChange={this.props.onChange}
onBlurResetsInput={false}
clearable= {false}
noResultsText= {null}
promptTextCreator= {(label) => {return formatMessage({ id: 'searchable.addNew' }) + ' ' + label;}}
autoBlur= {true}
onBlur={() => this.handleBlur()}
ref={this.setSelectorRef}
onFocus= {this.props.onFocus}
autosize= {false}
style= {this.props.style}
>
{this.props.children}
</Creatable>
);
};
};
来自放置此组件的其他文件的片段:
<Control
model=".assetTag"
component={SearchableSelect}
mapProps={{
value: props => props.viewValue
}}
controlProps={{
placeholder: 'device.assetTagPlaceholder',
options: this.state.assetTagOptions,
onChange: this.autoFillFields.bind(this),
onFocus: this.updateOptions.bind(this)
}}
style={{ border: this.state.missing.assetTag ? '1px dotted red' : '' }}
/>
【问题讨论】:
-
你想用 ref 做什么?将一个放在不是 DOM 元素的东西上没有意义。
-
@JJJ 我正在尝试从 react-select 获取对 Select 输入的引用,如此处所述 - github.com/JedWatson/react-select/issues/1764 重点是在 onBlur 事件上调用组件
createNewOption方法 -
@xadm 它不保留模糊值,只是输入。而且我不需要多选。我的解决方案有效,但控制台中的警告对其他开发人员来说只是额外的噪音,因为我实际上并没有尝试使用 ref 作为道具:D
-
为什么会有
CreatableSelect?这个来源?你能在 stackblitz 上创建minimal reproducible example 吗?
标签: reactjs ref react-select react-redux-form