简体   繁体   中英

ReactJS this.props not displaying

Im setting a simple property on a button, and trying to display it in the DOM... I dont understand what I'm doing wrong. I see Click Me! Current numer is Click Me! Current numer is , but not Click Me! Current numer is 1 Click Me! Current numer is 1 . I have to be missing something? No errors.

class TestElement extends Component {
    render(){
        return (
            <div>
                <Header />
                <div>
                    <button currentNumber={1}>Click Me! Current numer is {this.props.currentNumber}</button>
                </div>
                <Footer />
            </div>
        );
    }
}

React sends props down the chain. In TestElement.render() , this.props refers to any properties passed to the TestElement , eg:

class TestElement extends Component {
    render () {
        return (
            <span>My Name Is {this.props.name}</span>
        );
    }
}

rendered like so:

<TestElement name="One" />

Hopefully this shows that your line

<button currentNumber={1}>Click Me! Current numer is {this.props.currentNumber}</button>

is confusing what "this" element is. If you then rendered your TestElement with a currentNumber prop, it would appear on your button, but the currentNumber={1} attribute on the button will simply be ignored.

Edit

You could create a custom button something like this:

class MyCustomButton extends Component {
    render () {
        return (
            <button onClick={this.props.onClick}>Click Me!  Current number is {this.props.number} />
        );
    }
}

class TestElement extends Component {
    constructor () {
        this.state = {
            number: 1
        }
    }
    render () {
        return (
            <div>
                 <h1>The Buttonater!</h1>
                 <MyCustomButton number={this.state.number} onClick={this.onButtonClick} />
            </div>
        );
    }
    onButtonClick () {
        this.setState({
            number: this.state.number + 1
        });
    }
}

this.props is set for the instance of component you are defining . this refers to an instance of the class.

In this case this.props refers to the props for some instance of TestElement .

If you want to work with the props you pass to the button component, you'll have to define it as a child component.

class Button extends Component {
  render() {
    return (
      <button ...this.props>{this.props.currentNumber}</button>
    );
  }
}

Then instead use an instance of this component.

<Button currentNumber={1} />

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