我真的迷失了这个:
import React, { Component } from "react";
import Select from "react-select";
class selectDemo extends Component {
state = {
selectedOption: "",
data: [{ Model: "Option1" }, { Model: "Option2" }]
};
handleChange = selectedOption => {
this.setState({ selectedOption }, () =>
console.log(this.state.selectedOption.Model)
);
};
renderButton = () => {
return (
<button type="button" class="btn btn-primary">
{this.state.selectedOption.Model}
</button>
);
};
componentDidUpdate(prevProps, prevState) {
if (this.state.selectedOption !== prevState.selectedOption) {
this.renderButton();
}
}
render() {
const { selectedOption } = this.state;
const value = selectedOption && selectedOption.Model;
return (
<div>
<div name="selectedOption" className="section">
<Select
className="form-control"
placeholder="Select Option"
name="selectedOption"
value={value}
onChange={this.handleChange}
labelKey="Model"
valueKey="Model"
optionClassName="dropdown-item"
options={this.state.data}
/>
</div>
<div className="form-group">{this.renderButton}</div>
</div>
);
}
}
export default selectDemo;
我要实现的是,当我从使用react-select包创建的下拉列表中进行选择后,按钮就会呈现在页面上。一切正常,除了做出选择后按钮未呈现的事实。有人知道我错了吗?
答案 0 :(得分:0)
您在主this.renderButton
函数中缺少对render
的函数调用。看起来应该像这样:
<div className="form-group">{this.renderButton()}</div>
此外,在您的componentDidUpdate
中,您正在调用this.renderButton()
,但这不会导致它呈现返回的标记。 handleChange
的状态更新将触发组件的重新渲染,而无需您检入componentDidUpdate
。
答案 1 :(得分:0)
您必须显式调用renderButton this.renderButton()
这是正确的方法:
class SelectDemo extends React.Component {
state = {
selectedOption: "",
data: [{ Model: "Option1" }, { Model: "Option2" }]
};
handleChange = selectedOption => {
this.setState({ selectedOption }, () =>
console.log(this.state.selectedOption.Model)
);
};
renderButton = () => {
return (
<button type="button" className="btn btn-primary">
{this.state.selectedOption.Model}
</button>
);
};
render() {
const { selectedOption } = this.state;
const value = selectedOption && selectedOption.Model;
return (
<div>
<div name="selectedOption" className="section">
<Select
className="form-control"
placeholder="Select Option"
name="selectedOption"
value={value}
onChange={this.handleChange}
labelKey="Model"
valueKey="Model"
optionClassName="dropdown-item"
options={this.state.data}
/>
</div>
{this.state.selectedOption && <div className="form-group">{this.renderButton}</div>}
<div className="form-group">{this.renderButton()}</div>
</div>
);
}
}