我正在使用 react-select v2.0创建一个带有预定义项目的选择下拉列表。我将它连接到 Parse 查询,该查询通过文本搜索返回选项。
我的问题是我不知道如何将所选值传递给父组件。
该组件名为 RestaurantSelect
看起来像这样(删节):
import React, { Component } from 'react'
import AsyncSelect from 'react-select/lib/Async'
type State = {
inputValue: string
}
const filterRestaurants = (inputValue: string) => {
return (
// ... results from Parse query (this works fine)
)
}
const promiseOptions = inputValue => (
new Promise(resolve => {
resolve(filterRestaurants(inputValue))
})
)
export default class WithPromises extends Component<*, State> {
state = { inputValue: '' }
handleInputChange = (newValue: string) => {
const inputValue = newValue.replace(/\W/g, '')
this.setState({ inputValue })
return inputValue
}
render() {
return (
<AsyncSelect
className="select-add-user-restaurant"
cacheOptions
defaultOptions
placeholder="Start typing to select restaurant"
loadOptions={promiseOptions}
/>
)
}
}
调用RestaurantSelect
的父组件看起来像这样:
import React from 'react'
import RestaurantSelect from './RestaurantSelect'
class AddUserRestaurant extends React.Component {
constructor() {
super()
this.state = {
name: ''
}
}
addUserRestaurant(event) {
event.preventDefault()
// NEED INPUT VALUE HERE!
}
render() {
return (
<form onSubmit={(e) => this.addUserRestaurant(e)}>
<RestaurantSelect />
<button type="submit">Add</button>
</form>
)
}
}
export default AddUserRestaurant
如果我检查组件,我可以看到输入 value
属性匹配键入的文本,但是当从下拉列表中选择一个值时,它会消失(即从 <input value="Typed name" />
到 <input value />
。单独的 <span>
元素与标签的值一起出现,但我不想必须从 DOM 中获取它,这似乎不是预期的方法。
如果我在 React 控制台选项卡中搜索我的组件,RestaurantSelect
没有找到:
但是,如果我搜索 Select,它会出现并且有 props
和 state
具有选定值(在本例中为“Time 4 Thai”):
然而,console.log(this.state)
在 RestaurantSelect 中仅显示 inputValue
, 没有来自 <Select/>
有没有办法访问props
和 state
的高阶分量?
最佳答案
发现问题,在RestaurantSelect
handleInputChange
函数需要添加为onChange
支持返回的组件。像这样:
<AsyncSelect
className="select-add-user-restaurant"
cacheOptions
defaultOptions
placeholder="Start typing to select restaurant"
loadOptions={promiseOptions}
onChange={this.handleInputChange}
/>
newValue
是具有这种结构的对象:
{
value: "name",
label: "Name"
}
注意:激活后,上面的代码会抛出错误。我将其更改为将数据传递给父组件:
handleInputChange = (newValue: string) => {
this.props.setRestaurantSelection(newValue)
const inputValue = newValue
this.setState({ inputValue })
return inputValue
}
在哪里this.props.setRestaurantSelection
像这样来自父组件:
<RestaurantSelect setRestaurantSelection={this.setRestaurantSelection} />
在父组件中看起来像这样:
constructor() {
super()
this.state = {
restaurantSlug: ''
}
this.setRestaurantSelection = this.setRestaurantSelection.bind(this)
}
…
setRestaurantSelection = (value) => {
this.setState({
restaurantSlug: value.value
})
}
关于javascript - 如何访问 react-select HOC 的 props 和 state,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50103744/