javascript - how to use react-select list?
问题描述
I am new to react
and i want to use react-select
in a functional component. but always getting this error:
'handleChange' is not defined no-undef
'selectedOption' is not defined no-undef
'options' is not defined no-undef
below is the code inside a file Store.js
import React from 'react';
import Select from 'react-select';
function Store(){
React.useState({selectedOption: null})
handleChange = selectedOption => {
this.setState({ selectedOption });
};
return (
<div>
<div className='col-md-4' >
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
</div>
</div>
)
}
export default Store
解决方案
handleChange, selectedOption and options are not defined
import React from 'react';
import Select from 'react-select';
const options = [] //YOUR OPTIONS HERE
function Store(){
const [selectedOption, set_selectedOption] = React.useState('')
function handleChange(_selectedOption) {
set_selectedOption(_selectedOption)
};
return (
<div>
<div className='col-md-4' >
<Select
value={selectedOption}
onChange={handleChange}
options={options}
/>
</div>
</div>
)
}
export default Store
You should check the difference between a class/react Component where you can use this (this.setState({}), this.state.XXX, this.props) for example :
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
and a react hook function, where you can use hooks (no this) :
function Welcome(props) {
const [name, set_name] = useState('Hello');
return <h1>Hello, {props.name}</h1>;
}
推荐阅读
- reactjs - i18n 反应返回 [object 对象]
- vue.js - 如何在 Nuxt Vue 应用程序中重定向
- python-3.x - 将 Redis 中的字节字符串反序列化为 Python3 中的 dict 类型列表的最佳方法
- macos - 如何在 MacOS 上加密和解密 .zip 文件
- spring-boot - 使用 RabbitMQ 的微服务应用程序中的事件消费者数量
- python - 升级 pip 失败:尝试了“python -m pip install --upgrade pip”
- pine-script - PineScript (TradingView) 策略 X 分钟后关闭交易
- python-3.x - Azure Functions Python BadHttpRequestException - 读取请求正文超时
- io - 使用 openmp 读写一个非常大的文本文件
- php - Cake\ORM\Entity 的策略尚未定义