Yêu cầu thg 4 22, 2019 3:35 SA 556 0 1
  • 556 0 1
+1

how to set style when onpress change state in react native

Chia sẻ
  • 556 0 1

https://snack.expo.io/@dongcv/our-first-navigate-v3

các anh chị ơi em muốn set style khi state có thay đổi mà chưa tìm ra Mong các a chị chỉ giáo Em Xin Cảm Ơn !! ^_^

1 CÂU TRẢ LỜI


Đã trả lời thg 4 22, 2019 3:50 SA
Đã được chấp nhận
+1

theo mình hiểu là bạn đang muốn khi click vào item nào thì item đó opacity sẽ thành 1 đúng không nhỉ? Bạn thử viết state trong constructor nhá.

constructor(super) {
        this.state = {
             your_county:  0
        }
} 

và sự kiện click bạn nên cho nó thành 1 function nhá, function sẽ không cần render lại 1 function khác.

_onClick = (index) = () => {
       this.setState({your_coutry : index)}
}
 <TouchableHighlight onPress={this._onClick(item.index)} ....
Chia sẻ
thg 4 22, 2019 4:08 SA

"click vào item nào thì item đó opacity sẽ thành 1" đúng rồi anh ạ em thử các của anh rồi nhưng nó vẫn vậy ạ , vấn đề của em là State đã thay đổi nhưng style k đổi ạ

thg 4 22, 2019 4:29 SA

Nãy mình nhìn nhầm :v, bạn xem lại đoạn code này nhá, bởi vì renderItem chỉ render 1 lần lúc mới render, nên nó sẽ chỉ có state ban đầu và không thay đổi, bạn hãy truyền cho nó 1 props nhá

export default class Country extends Component {
  constructor(props) {
    super(props)
    this.state = {
      your_county: 2
    }
  }

  _onClick = (index) => () => {
    this.setState({your_county: index})
  }

  render() {
      return (
          <View style={ViewCss.container}>
              <View style={ViewCss.header} >
                  <Text style={ViewCss.h3text}>
                      Choose your country {this.state.your_county}
                  </Text>
              </View>
              <FlatList
                  data={data}
                  style={ViewCss.flatList}
                  itemSelected={this.state.your_county}
                  numColumns={2}
                  renderItem={this.renderItem()}
              />
          </View>
      );
  }

  renderItem = () => (item) => {
      return (
          <View style={itemCss.item}>
              <TouchableHighlight onPress={this._onClick(item.item.index)} underlayColor="white">
            <View style={[itemCss.row, this.state.your_county == item.item.index ? itemCss.highlight : itemCss.row]} >
                      <Text style={itemCss.text}>{item.item.key}</Text>
                  </View>
              </TouchableHighlight>
          </View>
      );
  };
}

thg 4 22, 2019 4:45 SA

@longnk1301 <View style={[itemCss.row,this.state.your_county === item.item.index ? itemCss.highlight : itemCss.row]} > thanks anh nhiều ạ

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí