Anish
Anish

Reputation: 391

Constructor inside React component

I am completely new to react native, Can you some one fix the following code.

Iam using a view inside const and i need to use constructor inside the const function

const { width } = Dimensions.get('window');
const tileWidth = width - 30;
const tileHeight = tileWidth * 0.50;
const tileHeight = tileWidth * 0.50;

    constructor(props) {
        super(props);

        this.state = {
            //tileViewWidth: null,
            tileViewHeight: null,
        }

        this.measureView = this.measureView.bind(this);
    }

    measureView(event) {
        // console.log('event properties: ', event);
        this.setState({
            //tileViewWidth: event.nativeEvent.layout.width,
            tileViewHeight: (event.nativeEvent.layout.height / 2) - 7,
        });
    }



const MyNavScreen = ({ navigation, banner }) => (

           <ScrollView style={styles.container} >

         <View style={css.home_tiles.container} onLayout={(event) => this.measureView(event)}>

<TouchableOpacity underlayColor="transparent" style={[{ width: tileWidth, height: this.state.tileViewHeight }]}> </TouchableOpacity> </View>);

Upvotes: 0

Views: 1185

Answers (1)

Meysam Izadmehr
Meysam Izadmehr

Reputation: 3262

You are trying to add a state to the stateless component. You can find many articles about their differences(for example this one). Use regular component instead of stateless component:

class GeneralButton extends Component {
  constructor(props) {
    super(props)

    this.state = {
      //tileViewWidth: null,
      tileViewHeight: null,
    }

    this.measureView = this.measureView.bind(this)
  }

  measureView(event) {
    // console.log('event properties: ', event);
    this.setState({
      //tileViewWidth: event.nativeEvent.layout.width,
      tileViewHeight: (event.nativeEvent.layout.height / 2) - 7,
    })
  }

  render() {
    return <ScrollView style={styles.container}>
      <View style={css.home_tiles.container} onLayout={(event) => this.measureView(event)}>
        <TouchableOpacity underlayColor="transparent" style={[{width: tileWidth, height: this.state.tileViewHeight}]}>
        </TouchableOpacity>
      </View>
    </ScrollView>
  }
}

Upvotes: 1

Related Questions