这里的功能是在数据库中调用 codigo 和 nombre 表注册。我要实现的是,当您选择代码时,就像自动完成功能一样填写姓名的数字代码。 enter image description here
class Matriculas extends Component {
state = {
status: "initial",
data: []
}
componentDidMount = () => {
this. getInfo()
}
getInfo= async () => {
try {
const response = await getAll('matriculas')
console.log(response.data)
this.setState({
status: "done",
data: response.data
});
} catch (error) {
this.setState({
status: "error"
});
}
};
render() {
const data = [...this.state.data];
return (
<Container>
<RowContainer margin="1px" >
<ColumnContainer margin="10px">
<h3>Info</h3>
<label>Codigo</label>
<Input
width='150px'
type="text"
placeholder="Digite el codigo"
value={data.codigo } ref="codigo" />
<label>Nombre</label>
<Input
width='150px'
type="text"
placeholder="Nombre completo"
value={data.nombre} />
</ColumnContainer>
</RowContainer>
</Container>
)
}
};
export default Matriculas;
答案 0 :(得分:0)
您最可能想使用的是react-select
您可以将选项传递给选择项(即您的名字),它将返回与您在搜索栏中键入的内容相匹配的值。
import Select from 'react-select'
const options = [
{ value: 'mike', label: 'Mike' },
{ value: 'john', label: 'John' },
{ value: 'vanessa', label: 'Vanessa' }
]
const MyComponent = () => (
<Select options={options} />
)
因此您可以将该示例以及链接中的示例放在代码中:
import Select from 'react-select'
<Container>
<RowContainer margin="1px" >
<ColumnContainer margin="10px">
<h3>Info</h3>
<label>Codigo</label>
<Input
width='150px'
type="text"
placeholder="Digite el codigo"
value={data.codigo } ref="codigo" />
<label>Nombre</label>
<Select
value={this.state.nameValue}
onChange={event => {this.setState({nameValue: e.value})}
options={options} />
</ColumnContainer>
</RowContainer>
</Container>
使用onChage时,它返回一个event
,其值为所选名称的值。您可以使用它来设置状态的nameValue,然后在其余组件中也使用该名称值
一旦启动并运行它,还值得研究async select,它允许您提供一个异步函数来返回值(例如,您的getInfo
函数)
-编辑-
如果要在其他地方定义onChange事件,则它看起来像这样:
handleChange = event => {
// event.value will be the value of the select
this.setState({optionSelected: event.value});
}
然后在您的onChange中,告诉它这是您想要的功能,但不要调用它(不要用括号写出来):
<Select
value={this.state.optionSelected}
onChange={this.handleChange}
options={options} />