【问题标题】:How to change the button text on fetch response in react native?如何在本机反应中更改获取响应的按钮文本?
【发布时间】:2018-06-03 17:30:29
【问题描述】:

我想根据服务器返回的响应更改按钮文本。怎么可能? 我的回复是这样的

{
"responseHeader": {
"type": "314",
"status": "200",
"message": "Successfully found the profile"
},
"neighbourProfile": [{
"no_of_mutual_friends": "0",
"is_anchored": "1",
},
{
"no_of_mutual_friends": "0",
"is_anchored": "0"
}]
}

我想根据状态 is_anchored 更改按钮文本,如果它是 0,我希望按钮文本为 friends 否则 add ,我该怎么做?这是我的反应部分

return (
      <Card>
      <CardSection>
      <Image style ={styles.thumbnail_style} source={{uri : profile_image_url}} />
       <View style= {styles.thumbnailContainerStyle}>
    <Text style={styles.userStyle}>{username}</Text>
        <Image source={require('./src/Images/profession_cell.png')}/><Text style={styles.textStyle}>
      No profession to show</Text>
      <Text style={styles.friendStyle}>{no_of_mutual_friends} Mutual friends</Text>
      </View>
      <View style={styles.buttonStyle}><Button color="#00BFA5" title="Add" onPress={() =>console.log("clicked")}>
      </Button></View>
      </CardSection>

      </Card>
    );

【问题讨论】:

    标签: json reactjs react-native jsx styling


    【解决方案1】:

    关于你之前的问题,在你设置邻居状态之后:

    .then((responseData) =>this.setState({neighbours: responseData.neighbourProfile}));
    

    你可以像这样渲染按钮:

    render() {
      return (
        <View>
        {
          this.state.neighbours.map( (neighbour) => {
            return (
              <Button title={neighbour.is_anchored == "0" ? 'friends' : 'add'} />
            )
          })
        }
        </View>
      );
    }
    

    这将显示简单的结果反映到邻居的is_anchored 值。

    更新 1:

    随着您的问题更新,那里似乎应该有一个变量is_anchored。那么它可能是:

    <Button color="#00BFA5" title={is_anchored == "0" ? 'friends' : 'add'} onPress={() =>console.log("clicked")} />
    

    【讨论】:

    • 我已经尝试了上面的方法,但是每个按钮都带有相同的文本friends。我需要在这里再次使用地图方法吗?
    • 我错过了在is_anchored 中添加引号,我没有注意到它是一个字符串。试试{is_anchored == "0" ? 'friends' : 'add'}
    • 我试过这个&lt;View style={styles.buttonStyle}&gt; { return this.state.neighbours.map(neighbours =&gt; &lt;Button title={neighbours.no_of_friends == "0" ? 'add' : 'friends'} /&gt; ); } &lt;/View&gt;,但出现语法错误
    • 你非常接近。删除 return 然后它应该可以工作。 &lt;View style={styles.buttonStyle}&gt; { this.state.neighbours.map( neighbours =&gt; &lt;Button title={neighbours.no_of_friends == "0" ? 'add' : 'friends'} /&gt; ) } &lt;/View&gt;
    • 可能是&lt;Button color={neighbour. no_of_friends == "0" ? "red" : "blue"} title={neighbour. no_of_friends == "0" ? 'friends' : 'add'} /&gt;
    猜你喜欢
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多