【问题标题】:React-Native: pressing the button twice only updates the this.setStateReact-Native:按两次按钮只会更新 this.setState
【发布时间】:2019-09-23 09:17:09
【问题描述】:

应用程序很简单.. 气体转换.. 我想做的是将Inputed Amount 乘以2,就好像它是公式一样。所以我有一个index.js,它是Parent,还有一个Calculate.component.js,负责所有的计算。我想要的是,index.jsinputed value 传递给component 并进行计算并再次将其传递给index.js 以显示计算出的金额。

Index.js

import React, { Component } from 'react';
import { Text } from 'react-native';
import styled from 'styled-components';
import PickerComponent from './Picker.Component';
import CalculateAVGAS from './Calculate.component';

export default class PickerAVGAS extends Component {
  static navigationOptions = ({ navigation }) => ({
    title: navigation.getParam('headerTitle'),
    headerStyle: {
      borderBottomColor: 'white',
    },
  });

  state = {
    gasTypeFrom: 'Gas Type',
    gasTypeTo: 'Gas Type',
    input_amount: '',
    pickerFrom: false,
    pickerTo: false,
    isResult: false,
    result: '',
  };

  inputAmount = amount => {
    this.setState({ input_amount: amount });
    console.log(amount);
  };

  onResult = value => {
    this.setState({
      result: value,
    });
    console.log('callback ', value);
  };

  render() {
    return (
      <Container>
        <Input
          placeholder="Amount"
          multiline
          keyboardType="numeric"
          onChangeText={amount => this.inputAmount(amount)}
        />
        <ResultContainer>
          <ResultText>{this.state.result}</ResultText>
        </ResultContainer>
        <CalculateContainer>
          <CalculateAVGAS
            title="Convert"
            amount={this.state.input_amount}
            total="total"
            titleFrom={this.state.gasTypeFrom}
            titleTo={this.state.gasTypeTo}
            // isResult={this.toggleResult}
            result={value => this.onResult(value)}
          />
        </CalculateContainer>
      </Container>
    );
  }
}

计算 VGAS / 分量

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

export default class CalculateAVGAS extends Component {
  static propTypes = {
    amount: PropTypes.string.isRequired,
    titleFrom: PropTypes.string.isRequired,
    titleTo: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
  };

  state = {
    totalVisible: true,
    result: '',
  };

  onPressConversion = () => {
    const formula = this.props.amount * 2;
    const i = this.props.result(this.state.result);
    this.setState({ result: formula });
    // console.log(this.state.result);
    console.log('func()');
  }

  render() {
    return (
      <ButtonContainer onPress={() => this.onPressConversion()}>
        <ButtonText>{this.props.title}</ButtonText>
      </ButtonContainer>
    );
  }
}

执行此操作后,setState 仅在按下 Convert button 两次 时更新

【问题讨论】:

    标签: react-native setstate


    【解决方案1】:

    您的问题是您想在父组件中显示信息,但您将该信息保存在子组件的状态中。 只需将数量和结果传递给无状态子组件 (CalculateAVGS)。

    通常最好让子组件保持“哑”(即展示性),并仅将它们需要显示的信息以及需要执行的任何功能作为道具传递。

    import React, {Component} from 'react';
    import styled from 'styled-components';
    
    export default class CalculateAVGAS extends Component {
      onPressConversion = () => {
        this.props.result(this.props.amount * 2);
      };
    
      render() {
        return (
          <ButtonContainer onPress={() => this.onPressConversion()}>
            <ButtonText>{this.props.title}</ButtonText>
          </ButtonContainer>
        );
      }
    }
    
    const ButtonContainer = styled.TouchableOpacity``;
    
    const ButtonText = styled.Text``;

    父组件如下:

    import React, {Component} from 'react';
    import {Text} from 'react-native';
    import styled from 'styled-components';
    import CalculateAVGAS from './Stack';
    
    export default class PickerAVGAS extends Component {
      static navigationOptions = ({navigation}) => ({
        title: navigation.getParam('headerTitle'),
        headerStyle: {
          borderBottomColor: 'white',
        },
      });
    
      state = {
        gasTypeFrom: 'Gas Type',
        gasTypeTo: 'Gas Type',
        input_amount: null,
        pickerFrom: false,
        pickerTo: false,
        isResult: false,
        result: null,
      };
    
      inputAmount = amount => {
        this.setState({input_amount: amount});
      };
    
      onResult = value => {
        this.setState({
          result: value,
        });
      };
    
      render() {
        return (
          <Container>
            <Input
              placeholder="Amount"
              multiline
              keyboardType="numeric"
              onChangeText={amount => this.inputAmount(amount)}
            />
            <ResultContainer>
              <ResultText>{this.state.result}</ResultText>
            </ResultContainer>
            <CalculateContainer>
              <CalculateAVGAS
                title="Convert"
                amount={this.state.input_amount}
                total="total"
                titleFrom={this.state.gasTypeFrom}
                titleTo={this.state.gasTypeTo}
                result={value => this.onResult(value)}
              />
            </CalculateContainer>
          </Container>
        );
      }
    }
    
    const Container = styled.View``;
    
    const ResultContainer = styled.View``;
    
    const ResultText = styled.Text``;
    
    const CalculateContainer = styled.View``;
    
    const Input = styled.TextInput``;

    【讨论】:

    • 我希望我可以,但需要更多 15 名声望才能投票:/
    • 我明白了 :( 但是我认为您可以通过单击 upvote/downvote 按钮下方的复选标记来接受答案。
    猜你喜欢
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 2020-10-23
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    相关资源
    最近更新 更多