截至目前,我有一个类为将被多次调用的组件生成所有列表。但是,用户是否可以仅选择一个具有相同ID的项目?
class Skills extends Component {
constructor(props) {
super(props);
this.img = props.src
this.name = props.name
}
render() {
return (
<React.Fragment>
<div>
<Row>
<Image src={this.img} style={skillIcon} rounded />
<div>
<h4>{this.name}</h4>
<ul className="sul">
<li id="lvl 1">1</li>
<li id="lvl 2">2</li>
<li id="lvl 3">3</li>
<li id="lvl 4">4</li>
<li id="lvl 5">5</li>
<li id="lvl 6">6</li>
<li id="lvl 7">7</li>
<li id="lvl 8">8</li>
<li id="lvl 9">9</li>
<li id="lvl 10">10</li>
<li id="lvl 11">11</li>
<li id="lvl 12">12</li>
<li id="lvl 13">13</li>
<li id="lvl 14">14</li>
<li id="lvl 15">15</li>
</ul>
</div>
</Row>
</div>
</React.Fragment>
);
}
}
例如,如果选择了ID为lvl 1的li,则下次有人单击具有相同再生成分的另一个lvl 1 li时,将取消选择先前的选择。
答案 0 :(得分:2)
您需要将用户选择存储在状态中,并在用户选择其他项目时更新状态。
状态可以通过两种方式处理。
// its better to have a array with levels
const levels = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
class Skills extends Component {
constructor(props) {
super(props);
this.state = {
selection:null
}
this.img = props.src
this.name = props.name
}
render() {
const {selection} = this.state
return (
<React.Fragment>
<div>
<Row>
<Image src={this.img} style={skillIcon} rounded />
<div>
<h4>{this.name}</h4>
<ul className="sul">
{levels.map((level) => {
const isSelected = selection === level;
return (
<li
id={`lvl ${level}`}
key={level}
onClick={() => setSelection(level)}
style={{
padding: isSelected ? 10 : 2,
backgroundColor: isSelected ? 'red' : 'white',
}}
>
{level}
</li>
);
})}
</ul>
</div>
</Row>
</div>
</React.Fragment>
);
}
}
function Skills() {
const [selection, setSelection] = useState(null);
return (
<>
<div>
<img src={img} />
<div>
<h4>{name}</h4>
<ul className="sul">
{levels.map((level) => {
const isSelected = selection === level;
return (
<li
id={`lvl ${level}`}
key={level}
onClick={() => setSelection(level)}
style={{
padding: isSelected ? 10 : 2,
backgroundColor: isSelected ? 'red' : 'white',
}}
>
{level}
</li>
);
})}
</ul>
</div>
</div>
</>
);
}
src
不是动态的,则只需分配一个常量变量,就像
const LOGO_URL = "url to logo"
const logoStyle = {
...some css
}
<Image src={LOGO_URL} style={logoStyle} />
function Skill(props){
const { levels } = props
return (
<>
{levels.map(i => {
...do anything
})}
</>
)
}
function RootComponent() {
const [rootState,setRootState] = useState(null)
return (
<SkillsOrAnyComponent updateState={setRootState} />
)
function SkillsOrAnyComponent(props){
const { updateState } = props
const changeMainState = (val) => {
updateState(val)
}
return ...some jsx
} }