【问题标题】:How to setState View style width to be +1 and height to be +1 in react native?如何在本机反应中将State View样式宽度设置为+1,高度设置为+1?
【发布时间】:2020-03-03 18:41:34
【问题描述】:

我想要这个框(视图)的样式宽度和高度 +1

我不写 style={{width:{{this.state.w}},height{{this.state.h}},backgroundColor:'blue'}}

export default class App extends Component { 

constructor(props){ 
 super(props); 
  this.state = { 
    w: 50, 
    h: 50, 
  } 
 } 

_addBox(){ 

  this.setState ({ 
      w:this.state.w + 1, 
      h:this.state.h + 1 
  });
}


 render() { 
  return ( 
  <view> 
   <view style="{{{styles.box}}}"> 
    <view style{{width:xxxx,height:xxxx,backgroundcolor:'blue'}}> 
     <text style="{styles.box}">
      {this.state.w}
     </text> 
    </view> 
    <buttontitle="add box"="" onpress="{this._addBox.bind(this)}" /> 
   </view> 
  </view> 
);
} 
}


帮帮我:(

【问题讨论】:

  • 嗨!请使用tour(您将获得徽章!),环顾四周,并通读help center,尤其是How do I ask a good question?,我还推荐Jon Skeet 的Writing the Perfect Question 和Question Checklist。完全不清楚你在这里问什么。
  • 当您提出问题时,文本区域右侧有一个橙色的大如何格式化框,其中包含有用的信息。还有一个工具栏,里面装满了格式化辅助工具。还有一个 [?] 按钮提供帮助。 和一个预览区域,显示您的帖子在发布时的样子,位于文本区域和“发布您的问题”按钮之间(这样您就必须滚动过去才能找到该按钮,以鼓励你去看看)。使您的帖子清晰,并证明您花时间这样做,可以提高您获得好答案的机会。 (我已经为你修好了。)

标签: javascript react-native


【解决方案1】:

如果你使用 setState 中的状态,那么推荐的方式是:

_addBox = () => {
    this.setState(prevState => ({
        w: prevState.w + 1,
        h: prevState.h + 1
    }))
}

在你的渲染函数中使用你的状态:

render() {
    const { w, h } = this.state
    return (
        <View>
            <View style={styles.box}>
                <View style={{ width: w, height: h, backgroundColor: 'blue' }}>
                    <Text style={styles.box}>{w}</Text>
                </View>
                <Button title="add box" onPress="{this._addBox}" />
            </View>
        </View>
    )
}

【讨论】:

  • 6666666666666~~~ O(∩_∩)O
  • 6666666666666~~~ O(∩_∩)O
猜你喜欢
  • 2017-01-30
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
  • 2016-03-09
  • 2014-02-09
  • 2020-06-29
  • 2016-01-29
  • 2017-02-05
相关资源
最近更新 更多