【发布时间】:2018-03-01 14:12:49
【问题描述】:
抱歉这个问题,我是 react 新手。
我有一个组件“QuickLaunch”,其中包含 2 个:一个基于 react-select 的组件“MySelect”和一个自定义数据表组件 (Datatable)。
Quicklaunch 中的渲染函数如下所示:
render() {
return (...
<MySelect item="lists" searchField="name" condition="list_type_id=1" multi={true} name="select-list"/>
...
<Datatable options={{...}}>
...)}
我需要向 react-select 组件添加一个项目(就像我在该 react-select 组件中选择一个项目一样)但是当我单击表中的一行时。我知道如何使用自定义组件来做到这一点,但我不能用 react-select 精确地做到这一点,因为我不想修改包的源代码。这可能吗 ? 这是 MySelect 来源:
import React from 'react'
//import PropTypes from 'prop-types';
import Msg from '../i18n/Msg'
import PropTypes from 'prop-types';
//https://jedwatson.github.io/react-select/
import Select from 'react-select';
import mtpSettings from '../../config/mtp4.json'
import { setRequestHeaders, formsForOptions } from '../../lib/mtp.js'
export default class MySelect extends React.Component {
constructor(props) {
super(props)
this.props = props
this.state = {value: ''};
}
// componentDidMount = () => {
// this.setState({
// value: '',
// })
// }
getOptions = (input) => {
if (!input) {
return Promise.resolve({ options: [] });
}
let fetchData = {
"headers": setRequestHeaders(),
"method": "GET"
}
//let url = mtpSettings.mtp4Config.apiBaseUrl + 'lists' + "?limit=50&" + "name" + "=%" + input + "%"
let url = mtpSettings.mtp4Config.apiBaseUrl + this.props.item + "?limit=50&" +
this.props.searchField + "=%" + input + "%&" + this.props.condition
return fetch(url, fetchData)
.then((response) => {
// console.log(response.json())
return response.json()
})
.then((items) => {
let options = formsForOptions(items, "id_list", "name")
return { options: options }
})
}
onChange = (value) => {
this.setState({
value: value,
})
}
render() {
//const AsyncComponent = this.state.creatable ? Select.AsyncCreatable : Select.Async;
/*<AsyncComponent multi={this.state.multi} value={this.state.value}
onChange={this.onChange} onValueClick={this.gotoUser} valueKey="id" labelKey="login"
loadOptions={this.getUsers} backspaceRemoves={this.state.backspaceRemoves} />
*/
return (
<div>
<Select.Async
name={this.props.name}
autoload={true}
value={this.state.value}
loadOptions={this.getOptions}
onChange={this.onChange}
backspaceRemoves={true}
multi={this.props.multi}
id={this.props.id}
/>
</div>
)
}
}
非常感谢!
【问题讨论】:
-
那么在表格中的行组件中添加一个处理程序/事件?或者,如果您可以进一步解释。
-
问题不是将处理程序添加到表中,而是更新 MySelect 组件以在我单击表中的行时为其添加选项
-
所以在你的处理程序中你可以更新/添加一些东西到你传递给选择的列表中。最好将此列表保留在父 QuickLaunch 组件中。
标签: javascript reactjs components