如何更改子组件的背景色

时间:2018-06-20 09:26:25

标签: javascript react-native

我实现了两个简单的react组件,如下所示:

用户组件(父):

export default class Users extends React.Component {

    constructor(props){
        super(props);
        this.state={
            users:[
                {id:1,name:'name1'},
                {id:2,name:'name2'},
                {id:3,name:'name3'},
                {id:4,name:'name4'}
            ]
        }
    }


    render(){
        return (
            <View>
                <Text>Users</Text>
                {this.state.data.map((user) => {
                    return <Card user={user}/>
                })}
            </View>
        )
    }
}

卡片组件(子):

class Card extends React.Component {

render(){
    return (
        <View>
            <Text>{this.props.user.name}</Text>
        </View>
    )
}

}

我想在点击时更改卡的背景颜色,

然后我尝试将Card组件更改为此:

class Card extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            BGClass: 'unselectedCard'
        }
    }

    select() {

        this.setState({BGClass: 'selectedCard'})
    }

    render() {
        return (
            <TouchableWithoutFeedback onPress={() => {
                this.select()
            }}>
                <View  style={styles[this.state.BGClass]}>
                    <Text>Card</Text>
                </View>
            </TouchableWithoutFeedback>
        )
    }
}

有了这个更改,当我点击Card时,Card的背景就改变了,但是我的问题是当新Card更改为选定的背景色时,另一张Card不会返回未选择的背景色,

1 个答案:

答案 0 :(得分:1)

您的问题与ES6类方法有关,默认情况下未绑定到类实例(请参见issue 9851

更改:

<TouchableWithoutFeedback onPress={() => {
    this.select()
}}>

收件人:

<TouchableWithoutFeedback onPress={this.select.bind(this)}>

或者(更好的方法)是在构造函数中添加以下行:

this.select = this.select.bind(this)

编辑

export default class Users extends React.Component {

    constructor(props){
        super(props);
        this.state={
            users:[
                {id:1,name:'name1'},
                {id:2,name:'name2'},
                {id:3,name:'name3'},
                {id:4,name:'name4'}
            ],
            selectedUserId: null,
        }
    }

    select(userId) {
        this.setState({selectedUserId: userId})
    }

    render(){
        return (
            <View>
                <Text>Users</Text>
                {this.state.data.map((user) => {
                    return <Card user={user} isSelected={user.id === this.state.selectedUserId} onSelect={this.select.bind(this)}/>
                })}
            </View>
        )
    }
}

class Card extends React.Component {
    render() {
        return (
            <TouchableWithoutFeedback onPress={() => {
                this.props.onSelect(this.props.user.id)
            }}>
                <View  style={!this.props.isSelected && styles['unselectedCard']}>
                    <Text>Card</Text>
                </View>
            </TouchableWithoutFeedback>
        )
    }
}