在选项卡上更改更新本机状态

时间:2019-08-19 13:17:25

标签: javascript reactjs react-native

在这里有两个选项卡invoice_specific和as_hoc,一个按钮在其中显示sum(this.state.sum)value。 默认情况下,当我以总和状态“ invoice_specific”值打开屏幕时,应该在下面的render函数中编写此值。 现在,如果我更改选项卡,我将调用函数handleChangeTab(),那么在更改选项卡时,我必须更新状态总和。 如果我在第一个选项卡中,invoice_specific值应显示,否则我在as_hoc选项卡中,则应在总和中分配此值。


constructor() {
    this.state = {
        sum: 0,
        invoice_specific: 0,
        as_hoc: 0
    }
    this.handleChangeTab = this.handleChangeTab.bind(this)
}
handleChangeTab=(obj) =>{ 
 console.log({ obj })
}

函数handleChangeTab()中obj的控制台值

{ i: 1, ref: {…}, from: 0 }
from: 0
i: 1
ref: $$typeof: Symbol(react.element)
key: ".1"
props:
  children: {
    $$typeof: Symbol(react.element),
    type: ƒ,
    key: null,
    ref: null,
    props: {…},
    …
  }
  heading: "AD-HOC"
  tabLabel: "AD-HOC"
  virtual: undefined

返回功能

render(){
  const viewStyle = {flexDirection: 'column', padding:10, backgroundColor: '#fff', minHeight:deviceHeight }
  return( 
    <Tabs onChangeTab={(obj)=> this.handleChangeTab(obj)}>
        <Tab heading="INVOICE SPECIFIC" tabLabel="SPECIFIC">
        <View style={viewStyle}>
            <RegularText text="Enter Specific Amount to pay" style={{paddingBottom:5}} textColor="#959595" />
            <View>
            <Item style={{borderColor: '#00fff', borderBottomWidth:1}}>
                <Input autoFocus={true} 
                       onPress={()=> this.handleChange('sumValue')} 
                       onChangeText={(sumValue) => this.handleChangeSum(sumValue)} />
            </Item>
            </View>
        </View>
        </Tab>
        <Tab heading="AD-HOC" tabLabel="AD-HOC">
        <View style={viewStyle}>
            <RegularText text="Enter Specific Amount to pay" style={{paddingBottom:5}} textColor="#959595" />
            <View>
            <Item style={{borderColor: '#00fff', borderBottomWidth:1}}>
                <Input autoFocus={true}
                       onPress={()=> this.handleChange('sumValue')}
                       onChangeText={(sumValue) => this.handleChangeSum(sumValue)} />
            </Item>
            </View>
        </View>
        </Tab>
    </Tabs> 
  ) 
}

1 个答案:

答案 0 :(得分:0)

我没有看到您在任何地方都调用过setState()。您需要适当地调用setState,同时避免无限重新渲染。另外,如果可以走得更远,然后将其更改为功能组件,可以在其中找到ref和useEffect,使代码更简单易读。