简体   繁体   中英

Not rendering component onClick

The component I am trying to render:

import React, { Component } from 'react';

export default class QueryPrint extends Component {

    render() {
        console.log('working');

        return (
            <div>Hello</div>
        )
    }

}

The component that is trying to call it:

import React, { Component } from 'react';
import { connect } from 'react-redux';

import {
    Button,

} from 'reactstrap';

import QueryPrint from './bq_print';

class QueryResults extends Component {
    constructor(props) {
        super(props);
        this.print = this.print.bind(this);
    }

    print() {
        console.log('Clicked');
        return (
            <QueryPrint />
        );
    }

    render() {
        return (
            <Button 
                className='cuts-btn' 
                color='success' 
                onClick={this.print}
            >
                Print
            </Button>
        )
    }
}

function mapStateToProps(state) {
    return {
        query_data: state.results.query_data
    }
}

export default connect (mapStateToProps, null)(QueryResults);

The console.log('clicked') is working, but the component that is supposed to render in that method doesn't--no console.log('working') or <div> .

Returning something from a click callback has no effect. If you want to render something, you do so in the render method. The click callback's job is to call this.setState(), which will then kick off a render.

Perhaps something like this:

class QueryResults extends Component {
  constructor(props) {
    super(props);
    this.print = this.print.bind(this);
    this.state = {
      queryPrint: false,
    }
  }

  print() {
    console.log('Clicked');
    this.setState({ queryPrint: true })
  }

  render() {
    const { queryPrint } = this.state;
    return (
      <React.Fragment>
        {queryPrint && <QueryPrint />}
        <Button 
          className='cuts-btn' 
          color='success' 
          onClick={this.print}
        >
          Print
        </Button>
      </React.Fragment>
    )
  }
}

React Native works differently. It is more like a web app - you need to navigate to the other component.

Look at this example its very to the point: https://facebook.github.io/react-native/docs/navigation

Alternatively if you want to make only part of the screen change you will need to include it into your own render and control it thru a flag or a state machine.

https://facebook.github.io/react-native/docs/direct-manipulation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM