如何访问componentWillMount()中的变量

时间:2018-05-08 07:54:04

标签: reactjs react-native

我正在尝试从componentWillMount()设置一个全局样式变量,但我无法做到这一点。当我记录变量时,它表示未定义。

export default class Post extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      postImageUri: {
        uri: this.props.postImageUri
      }
    }
  }

  componentWillMount() {
    Image.getSize(this.props.postImageUri, (width, height) => {
      ...
      styles.postImage.height = height
      styles.postImage.width = Dimensions.get('window').width
      console.log(styles.postImage.height)           //Undefined
      console.log(styles.postImage.width)            //Undefined
      ...
    });
  }

  render() {
    return (
      <View>
        <Image source={this.state.postImageUri} style={styles.postImage}/>
      </View>
  }
}

val styles = StyleSheet.create({
  postImage: {
    height: 0,
    width: 0
  }
})

2 个答案:

答案 0 :(得分:0)

不应改变样式,而应将高度存储在状态:

state = {
  height: null,
};

componentDidMount() {
  Image.getSize(this.props.postImageUri, (width, height) => {
    this.setState({ height });
  });
}

然后使用样式合成来应用状态的高度:

<Image 
  source={this.state.postImageUri} 
  style={[styles.postImage, { height: this.state.height } ]}
/>

您的宽度计算是同步的,因此您可以直接在样式中设置它:

const styles = StyleSheet.create({
  postImage: {
    width: Dimensions.get('window').width,
  },
});

答案 1 :(得分:0)

将样式存储在状态中,而不是存储在全局变量中。这样,无论何时更改状态并且组件将重新渲染,组件本身都会计算出来。

您可以使用this.setState({stateName: someValue});更改状态。