如何在ReactJS中使用onclick选择动态子元素的属性[选中]

时间:2018-12-14 03:01:41

标签: reactjs jsx

我正在使用复选框创建具有多项选择的下拉菜单, 我在下拉菜单的MenuItem中使用过onClick,因此用户可以单击复选框父级的MenuItem进行检查和取消选中,而不是完全单击复选框,下面的代码有效,当出现以下情况时,我可以获得复选框的选中状态我用静态值渲染它。 相同的是行不通的,我尝试使用动态值,例如使用数组引用-FilterMultipleItems组件,我在event.target.checked的handleChange方法中变得未定义,我是新来的人,任何人都可以指导我,谢谢。

class CustomButton extends React.Component {

    render() {
      const { onPress, isChecked, values} = this.props;      
      return (
        <MenuItem onClick={onPress}>
        <Checkbox
            disabled
            checked={isChecked}                        
            value={values}/>    {values}         
        </MenuItem>
      );
    }
  }

class FilterMultipleItems extends React.Component {

  state = {open: false,}

  constructor(props) {
    super(props)
   this.handleChange = this.handleChange.bind(this)
  }

  handleChange = name => event => {        
   console.log(name, event.target.checked) 
   //event.target.checked getting undefined
  }


render() {
const { classes, value } = this.props;
const { open } = this.state;

 // here I'm adding the dynamic values to the CustomButton Component

var filtersItems=[];
for(var i=0;i<this.props.value.filtersValues.length;i++){
    var currentItem = this.props.value.filtersValues[i];
    this.state[currentItem]= false;
    filtersItems.push( <CustomButton onPress={this.handleChange(currentItem)} values={currentItem} checked={this.state[currentItem]} key={i}>Click on me</CustomButton>)
}

return (
  <MenuList>
    {/*rendering the component here*/}
     {filtersItems}
  </MenuList>
);
} 

}

0 个答案:

没有答案