我有2个按钮,当我单击其中一个按钮时,该组件将显示在tr className =“ info”中。编写该代码是为了使它具有通用性,如果有50个不同的组件,那么将有50个不同的按钮。并且活动按钮将更改班级。我现在正尝试在道具的帮助下进行操作,我只是在学习,请告诉我,错误在哪里?
import React, { Component } from 'react';
import './App.css';
import Donald from '/.Donald';
import John from '/.John';
const Counter =({buttonType,id})=>{
const {
buttonType,
children,
} = props;
return (
<div
className = {`${buttonType}`}
onClick={id}
>
{children}
</div>
);
}
Counter.defaultProps={
className = 'notActive'
}
class MyName extends Component {
state = {
array:[
{id:1,component:<Donald/>, name:"My name Donald"},
{id:2,component:<John/>, name:"My name John"},
],
};
render() {
const selectedElement = this.state.array.find(item => item.id === this.state.currComponentId);
return(
<table>
<tbody>
<tr className="trButton">
{
this.state.array.map( (element) => {
return (
<Counter>
<td
className={'active'}
onClick={ () => this.element.id}
>{element.name}
</td>
</Counter>
)
})
}
</tr>
<tr className="info">
{selectedElement.component}
</tr>
</tbody>
</table>
)
}
}
export default MyName;
答案 0 :(得分:0)
我看到代码有几个问题
(1)首先,我认为您使用了错误的路径来导入这些组件,即使用./Donald
而不是/.Donald
(请注意.
之前的{ {1}}之后),类似/
。
(2)其次,您没有为状态中的'./John'
设置初始值。让我们也设置
currComponentId
(3)另外,我认为您正在尝试更改state = {
array:[
{id: 1, component: <Donald/>, name:"My name Donald"},
{id: 2, component: <John/>, name:"My name John"},
],
currComponentId: 1
};
中的currComponentId
。这样吧
onClick