RN中 通过callback 改变state

class testNetworkModel {
    constructor(callback) {
        this.callback = callback;
    }
    callback:Function = null;

    getCheckCode = () => {
        NetWorkTool.getCheckCode(
            (res) => {
                if (res && res.data && res.data.captcha) {
                    if (this.callback && typeof this.callback === 'function') {
                        this.callback(res.data.captcha);
                    }
                }
            }, (err) => {
                console.log('code err:', err);
            }
        )
    }
}

export default class App extends Component {
    constructor(props) {
        super(props);
        this.model = new testNetworkModel(this.getImage);
        this.state = {
            imageUrl: '',
        };
    }
    model = null;

    getImage = (sourceUrl) => {
        this.setState({
            imageUrl: sourceUrl,
        });
    };

  render() {
    return (
      <View style={styles.container}> 
          <TouchableOpacity
              activeOpacity={1.0}
              onPress={this.model.getCheckCode}
              style={styles.check_image_btn}
          >
              <Image
                  source={{ uri: this.state.imageUrl, cache: 'reload' }}
                  style={{ width: 140, height: 45 }}
                  resizeMode={'contain'}
              />
          </TouchableOpacity>
      </View>
    );
  }
}


猜你喜欢

转载自blog.csdn.net/mscinsidious/article/details/80048334