[英]React Bootstrap Dropdown Button OnSelect
我將選項值傳遞給一系列下拉按鈕,每個按鈕都位於數據數組的子組件中。
當在按鈕之一中選擇一個選項時,我將使用onSelect的結果更新父組件中的狀態。 一切都很好...
//parent component
sourceSelected = (event) => {
this.setState({
sourceSelected: event
});
...
<ButtonToolbar>
{MEDIUM.map((medium) =>
<Medium key={medium.medium_name} medium={medium} onSelectedValue{this.sourceSelected } />
)};
</ButtonToolbar>
//child component
<DropdownButton title={props.medium.medium_name} id="source-dropdown" onSelect={props.onSelectedValue}>
{props.medium.source.map((option, index) =>
<MenuItem key={index} eventKey={option}> {option} </MenuItem>)}
</DropdownButton>
但是,我還想在狀態(mediumSelected = ???)中存儲從中選擇選項的按鈕的名稱。
無論如何,有沒有讓OnSelect將其傳遞回去,還是我應該做其他事情?
您可以利用Javascript事件和this
。 基本上, 將事件傳遞給將使用按鈕名的函數,像這樣
<button name="btn" onClick={e => this.buttonName(e.target.name)}>
您還需要this
綁定到您的constructor()
示例代碼:
constructor(props) {
super(props);
// Bind this so you can use it below
this.buttonName = this.buttonName.bind(this);
}
buttonName(e) {
console.log(e);
}
render() {
return (
<div>
// Pass the name of the button to the function
<button name="btn" onClick={e => this.buttonName(e.target.name)}>
Button
</button>
</div>
);
}
我還在https://codesandbox.io/s/lrwqr303vz上舉了一個簡單的例子。 不用介意文件名。
好的,我使用... https://reactjs.org/docs/handling-events.html將參數傳遞給事件處理程序來回答這個問題。
代碼是:
//parent component
sourceSelected = ( medium_name, event) => {
this.setState({
sourceSelected: event,
mediumSelected: medium_name
});
}
...
<div className='test'>
<ButtonToolbar>
{MEDIUM.map((medium) =>
<Medium key={medium.medium_name} medium={medium} onSelectedValue={this.sourceSelected.bind(this, medium.medium_name) } />
)};
</ButtonToolbar>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.