React semantic-ui Dropdown onChange not working

眉间皱痕 提交于 2019-12-11 06:45:58

问题


Here's the code:

class MenuContainerComponent extends Component {

    onInputWidgetMenuChange(event, data) {
        console.log(data);
    }

    render() {
        var inputWidgets = [];
        for (var i = 0; i < this.props.cdata.widgets.inputWidgets.length; i++) {
            var componentName = getComponentNameFromType(this.props.cdata.widgets.inputWidgets[i]);
            var key = "inputWidget" + i;
            inputWidgets.push(<Dropdown.Item key={key}>{componentName}</Dropdown.Item>);
        }

        return (
        <Dropdown style={childStyle} text='Input widgets' icon='keyboard' floating labeled button className='icon' onChange={this.onInputWidgetMenuChange}>
            <Dropdown.Menu>
                <Dropdown.Header icon='tags' content='Select a widget to add to canvas' />
                <Dropdown.Divider />
                {inputWidgets}
            </Dropdown.Menu>
        </Dropdown>
        )
}

I am trying to get an event on menu selection. 'onClick' is working in similar fashion but there is no event on menu selection.


回答1:


AFAIK, since you're using Dropdown.Menu inside this Dropdown, the onChange won't work. It's for normal Drodowns (like selecting a value etc). Try creating a generic onClick and assign it to <Dropdown.Item />




回答2:


Giri's answer is correct. Change this line

inputWidgets.push(<Dropdown.Item key={key}>{componentName}</Dropdown.Item>);

to

inputWidgets.push(<Dropdown.Item key={key} value={componentId} onClick={this.onInputWidgetMenuChange}>{componentName}</Dropdown.Item>);

Where componentId is the actual value of the Dropdown.Item, (as opposed to the text displayed). Given the right circumstances componentId can be the same as the componentName too.

Another thing is that since you're using Dropdown.Menu inside the Dropdown, clicking the items on the menu won't automatically change the value of the Dropdown. (which is why the onChange of event the Dropdown component isn't fired). You need to save the current value of the Dropdown in the react state and manually set the trigger prop of Dropdown to make it look like the selected item.



来源:https://stackoverflow.com/questions/48252645/react-semantic-ui-dropdown-onchange-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!