反应this.props为null

时间:2017-01-10 12:30:44

标签: javascript reactjs

我有以下内容:

import React from 'react';
import {render} from 'react-dom';

class TShirt extends React.Component {
    render () {
        return <div className="thsirt">{this.props.name}</div>;
    }
}

class FirstName extends React.Component {
    propTypes: {
        name: React.PropTypes.string.isRequired
    }
    constructor(props) {
        super(props);
        this.state = {
            submitted: false
        };
    }
    getName () {
        var name = this.refs.firstName.value;
        this.setState(function() {
          this.props.action(name);
        });
    }
    handleSubmit (e) {
        e.preventDefault();
        this.setState({ submitted: true }, function() {
            this.props.actionNav('color');
        });
    }
    render () {
        if(!this.state.submitted){
            return (
                <div>
                    <h2>tell us your first name</h2>
                    <form>
                        <input 
                            type="text"
                            ref="firstName"
                            onChange={this.getName.bind(this)}
                        />
                        <div className="buttons-wrapper">
                            <a href="#">back</a>
                            <button onClick={this.handleSubmit.bind(this)}>continue</button>
                        </div>
                    </form>
                </div>
            );
        }
        else {
             return <PickColor color={this.props.colorVal} />;
        }
    }
}

class Link extends React.Component {
    setActiveClass () {
        if(this.props.el == this.props.activeClass){
            return 'active';
        }
    }
    render () {
        var active = this.setActiveClass();
        return (
            <li className={active}>{this.props.el}</li>
        );
    }
}

class Nav extends React.Component {
    render () {
        var links = ['name', 'color', 'design', 'share'],
            newLinks = [],
            that = this;
        links.forEach(function(el){
            newLinks.push(<Link activeClass={that.props.active} key={el} el={el} />);
        });
        return (
            <ul>
                {newLinks}
            </ul>
        );
    }
}

class PickColor extends React.Component {
    getColorValue(event) {
        console.log(event.target.getAttribute("data-color"));
        console.log(this);
        //this.props.color(event.target.getAttribute("data-color"));
    }
    render () {
        var colors = ['red', 'purple', 'yellow', 'green', 'blue'],
            colorsLink = [],
            that = this;

        colors.forEach(function(el){
            colorsLink.push(<li data-color={el} key={el} onClick={that.getColorValue} ref={el}>{el}</li>);
        });

        return (
            <ul>
                {colorsLink}
            </ul>
        );
    }

}

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            name: '',
            color: '',
            active: ''
        };
        this.getName = this.getName.bind(this);
        this.setActiveNav = this.setActiveNav.bind(this);
        this.setColor = this.setColor.bind(this);
    }
    getName (tshirt) {
        this.setState({ name:tshirt })
    }
    setActiveNav (active) {
        this.setState({ active:active })
    }
    setColor (color) {
        this.setState({ color:color })
    }
    render () {
        return (
            <section className={this.state.color}>
                <Nav active={this.state.active} />
                <TShirt name={this.state.name} />
                <FirstName name={this.state.name} action={this.getName} actionNav={this.setActiveNav} colorVal={this.setColor} />
            </section>
        );
    }
}

render(<App/>, document.getElementById('app'));

在&#34; PickColor&#34;我试图这样做:

getColorValue(event) {
    console.log(event.target.getAttribute("data-color"));
    console.log(this);
    //this.props.colorVal(event.target.getAttribute("data-color"));
}

然而,这在点击时返回null,因此我无法继续使用:

this.props.colorVal

3 个答案:

答案 0 :(得分:2)

解决方案在这里:

class PickColor extends React.Component {
    getColorValue(event) {
        console.log(event.target.getAttribute("data-color"));
        this.props.color(event.target.getAttribute("data-color"));
    }
    render () {
        var colors = ['red', 'purple', 'yellow', 'green', 'blue'],
            colorsLink = [],
            that = this;

        colors.forEach(function(el){
            colorsLink.push(<li data-color={el} key={el} onClick={that.getColorValue.bind(that)} ref={el}>{el}</li>);
        });

        return (
            <ul>
                {colorsLink}
            </ul>
        );
    }
}

我必须将“that”绑定到forEach循环中的onClick

答案 1 :(得分:1)

问题出在这一行:

onClick={that.getColorValue}

您忘记使用onClick事件处理函数绑定正确的this(类上下文),因为this.props函数无法访问getColorValue

<强>解决方案:

可以使用多个解决方案,使用任何一个(所有这些更改都适用于PickColor组件):

1 - 点击处理程序的内联绑定:

onClick = { that.getColorValue.bind(this) }

2 - 在构造函数中绑定方法:

constructor(props) {
    super(props);
    this.state = { };
    this.getColorValue = this.getColorValue.bind(this);
}

3 - 使用arrow function

onClick = {e => that.getColorValue(e) }

4 - 使用 class property syntax

onclick = {this.getColorValue}

getColorValue = (e) => {
   console.log('e', this.props)
}

答案 2 :(得分:0)

创建新功能时,如下所示:

function() {
    this.props.action(name);
});

这是绑定到新的函数上下文。每个函数在javascript中都有不同的this。您可以通过以下几种方式解决此问题:

如果你有箭头功能(他们不会重新绑定),请使用箭头功能

() => {
    this.props.action(name);
});

使用bind重新绑定

function() {
    this.props.action(name);
}.bind(this));

this保存在变量

var that = this;
function() {
    that.props.action(name);
});

如果您有像babel一样的转发器,请选择第一个!否则就是你的电话。