动态更改变量名称的一部分?

问题描述 投票:-3回答:3

在React中,是否可以根据状态动态更改变量名称的一部分?

例如,我从JSON文件中提供了几个组件信息。根据所选择的性别(男性或女性),我想从“male_clothes.js”或“female_clothes.js”发送“atlas”。

JSX代码:

class App extends Component {
    constructor(props) {
        super(props)
        this.state = {
            current_gender: "male",
            current_pants: 0,
        }
<LimbSegment atlas={male_clothes[this.state.current_pants]['atlas']}/>
reactjs
3个回答
1
投票
const { current_pants, gender } = this.state // I assume gender is comming from the state
const clothes = gender === 'male' ? male_clothes : female_clothes
const atlas = clothes[current_pants].atlas
// Then:
<LimbSegment atlas={atlas}/>

0
投票

不确定我是否理解正确。因此,如果state.gendermale它将使用male_clothes否则female_clothes

<LimbSegment atlas={this.state.gender === 'male' ? 
male_clothes[this.state.current_pants]['atlas'] : 
female_clothes[this.state.current_pants]['atlas']}/>

0
投票

短一点:

<LimbSegment atlas={(this.state.someFlag ? male_clothes : female_clothes)[this.state.current_pants]['atlas']}/>

但最好采用更冗长的方法:

const clothes = this.state.someFlag ? male_clothes : female_clothes;
...
<LimbSegment atlas={clothes[this.state.current_pants]['atlas']}/>
© www.soinside.com 2019 - 2024. All rights reserved.