我有几个div,每个div中都有一个图像,并且在包装div上有一个onCLick,它执行两个功能-clickHandler()
和toggleCollapse2()
。这个想法是div中的图像代表样式化的勾选框,该框用onClick替换了空框的图像。开头的onclick位于图像上,但是当我将Onclick放在包装的div上时,单击div时无法更改图片的来源。我将div放在了一个下拉项中,因为我有大约20个带有带打勾图标的带有文本标记图标的按钮,并且我试图重写React中的代码,但是不幸的是,我还是React的新手。因此,感谢您的帮助。想法是使用此代码,而不是用onClick和功能一个接一个地编写所有按钮。此外,带有文本的勾选图标必须位于3列中。
问题是单击div时使checkbox-yellow
替换checkbox_empty
图片。
//in the constructor
//constructor(props) {
// super(props);
//this.state = {
buttons :
[
{id:1, name:"check1", isVisited: false, value:"name1"},
{id:2, name:"check2", isVisited: false, value:"name2"},
{id:3, name:"check3", isVisited: false, value:"name3"},
{id:4, name:"check4", isVisited: true, value:"name4"},
{id:5, name:"check5", isVisited: false, value:"name5"},
{id:6, name:"check6", isVisited: false, value:"name6"},
{id:7, name:"check7", isVisited: true, value:"name7"},
{id:8, name:"check8", isVisited: false,value:"name8"},
{id:9, name:"check9", isVisited: false,value:"name9"},
{id:10, name:"check10", isVisited: false, value:"name10"},
{id:11, name:"check11", isVisited: false, value:"name11"},
{id:12, name:"check12", isVisited: false, value:"name12"},
{id:13, name:"check11", isVisited: false, value:"name13"},
{id:14, name:"check12", isVisited: false, value:"name14"}
],
//Outside the constructor:
dropdownButton(startIndex,endIndex){
let uiButtons = [];
this.state.buttons.slice(startIndex,endIndex).map((button)=>{
uiButtons.push(
<DropdownItem>
<div key={button.id} className="checkbox-business" onClick={() => {
this.clickHandler();
this.toggleCollapse2(button.name, button.isVisited)}} >
<img style={{maxWidth: '20px'}} src={button.isVisited === true ? checkbox_yellow : checkbox_empty}/>
<div>
{button.value}
</div>
</div>
</DropdownItem>
);
}
);
return uiButtons;
}
toggleCollapse2 = (sectionName) => {
this.setState({check1: false, check2: false, check3: false, check4: false})
let obj = {};
obj[sectionName] = !this.state[sectionName];
this.setState(state => (obj));
}
//in the render I have this code:/because I want the buttons distributed equally in 3 columns/
let startIndexFirstColumn = 0;
let endIndexFirstColumn = 0;
let startIndexSecondColumn = 0;
let endIndexSecondColumn = 0;
let startIndexThirdColumn = 0;
let endIndexThirdColumn = 0;
if ( this.state.buttons.length % 3 === 2) {
endIndexFirstColumn = (this.state.buttons.length / 3 + 1);
startIndexSecondColumn = (this.state.buttons.length / 3 + 1);
endIndexSecondColumn = ((this.state.buttons.length / 3) * 2 + 1);
startIndexThirdColumn = ((this.state.buttons.length / 3) * 2 + 1);
endIndexThirdColumn = (this.state.buttons.length / 3 * 3);
}
//and in the return part I have 3 similar divs,containing:
<div className="box-business">
{this.dropdownButton(startIndexFirstColumn,endIndexFirstColumn)}
</div>
//with different indexes for each column
答案 0 :(得分:0)
当单击包含图像和文本的div时,我需要使img源显示checkbox_yellow图像而不是checkbox-empty图像。并在再次单击div时将其更改回原来的状态。