简体   繁体   中英

Like button on React Native? I can't make it dynamically update

class PostButtons extends Component {
  constructor() {
    super();
    this.state = {
      liked: true,
    };
  }

  likeToggled() {
    this.setState({
      liked: !this.state.liked,
    });
  }

  render() {
    const heartIconColor = () => {
      if (this.state.liked === true) {
        return "red";
      } else if (this.state.liked === false) {
        return "black";
      }
    };



        <View>
          <TouchableOpacity
            onPress={() => {
              this.likeToggled;
            }}
          >
            <Image
              style={{
                height: 37,
                width: 37,
                marginVertical: 395,
                marginHorizontal: 10,
                justifyContent: "flex-start",
                position: "absolute",
                tintColor: heartIconColor(),
              }}
              source={require("../Img/Heart3.png")}
            ></Image>
          </TouchableOpacity>
        </View>

I need it so when someone clicks the like button (initial state is black) it turns red then when they click it again it goes back to black. Currently i need to change this.state.liked to true and false to change the colours. I am not that advanced so an answer thats not verbose would be greatly appreciated. Thanks

you weren't calling your likeToggled function. you were just accessing its definition which doesn't run the code inside your likeToggled function calling it like likeToggled() does

 <TouchableOpacity onPress={() => { this.likeToggled();}} >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM