reactjs - 为什么我不能使用我选择的选项的值?
问题描述
我正在构建一个包含两个选择的表单:一个用于 Gitlab 项目列表,另一个用于 Clockify 项目列表。在每个选择中,我的选项都是一个项目数组,标签是项目名称,值是项目 ID。
class NewDashboard extends Component {
constructor(props) {
super(props)
this.state = {
gitlabId: '',
clockifyId: ''
}
}
handleChange = event => {
change({ 'gitlabId': event.target.value, 'clockifyId': event.target.value })
};
render() {
const { gitlabId, clockifyId } = this.props.form
const { projects, projTime } = this.props
if (projects) {
gitlabProjs = projects.map(project => ({
value: project.id,
label: project.namespace.name + ": " + project.name,
}));
console.log(gitlabProjs)
}
if (projTime) {
clockifyProjs = projTime.timeEntries.map((timeEntry) => ({
value: timeEntry.project.id,
label: timeEntry.project.name,
}));
// console.log(clockifyProjs)
}
...
问题是:我似乎无法访问我选择的选项值(项目 ID),因为它返回未定义。
<Select
value={gitlabId.value}
type="search"
options={gitlabProjs}
onChange={e => {
change({ 'gitlabId': gitlabProjs.value })
console.log(gitlabProjs.value)
}}
placeholder="Projeto no Gitlab..."
></Select>
我可能这样做是错误的。有谁知道问题可能是什么?(我是反应初学者)。
解决方案
prop 需要一个函数,该onChange
函数接受所选值作为第一个参数(类型:)One of <Object, Array<Object>, null, undefined>
。所以使用event.target.value
没有效果。
道具本身也value
接受一个对象,它将显示为选定的值。因此,您可以保存整个选项对象并将其提供给value
道具:
handleChange = (option) => {
change({'gitlabId': option, 'clockifyId': option});
}
<Select
{ ... }
value={gitlabId}
onChange={this.handleChange}
/>
或者您可以保存选项的值,然后过滤您的选项数组以找到所选值:
handleChange = (option) => {
change({'gitlabId': option.value, 'clockifyId': option.value});
}
<Select
{ ... }
value={gitlabProjs.find((val) => val.value === gitlabId)}
onChange={this.handleChange}
/>
另外附注:该道具type
没有效果,因为组件不需要它Select
。
编辑:参考:react-select
道具文档
推荐阅读
- microsoft-teams - MS Teams Bot 操纵来自用户的音频流
- google-apps-script - Google Sheet Script:有没有办法在不停止脚本的情况下显示消息?
- javascript - Angular:通知不同组件之间的嵌套属性更改的正确方法
- php - foreach 循环中的 Phpspreadsheet 工作表在 PHP 中不起作用
- javascript - 这些 JavaScript 类定义有缺点吗?
- javascript - 在数组谷歌应用脚本javascript中间推送空白行
- android - 未连接适配器;跳过布局(Recyclerview)
- firebase - 禁用 auth/user-not-found 功能
- flutter - 未来类型递归函数无法正常工作
- express - 在快速边缘迭代数字类型?