React not passing along properties when rendering in variable

谁都会走 提交于 2019-12-13 17:56:37

问题


I'm writing a reusable component for menu itens, but React is not passing along the properties to the HTML when I render it in a variable. I'm using Browserify with the reactify tranform.

Here is the component code:

var React = require('react');
var ReactPropTypes = React.PropTypes;



var Menu = React.createClass({

  propTypes: {
    route: React.PropTypes.string,
    key: React.PropTypes.string.isRequired
  },

  render: function() {
    //alert(this.props.route);
    var routeName = this.props.route;
    var content = null;
    if (routeName) {
        content = (<a href="{routeName}">
                      {this.props.children}
                   </a>);
    } else {
        content = (<a>{this.props.children}</a>);
    }
    return (<li key="{this.props.key}">{content}</li>);
  }

});


module.exports = Menu;

The final HTML output is:

<li data-reactid=".0.0.2.0.$home">
    <a href="{routeName}" data reactid=".0.0.2.0.$home.0">Home</a>
</li>

The key property is function properly, but the route property is not (the value is correct, but it is not rendering the way it should).

If I change the render method to:

render: function() {
    //alert(this.props.route);
    var routeName = this.props.route;
    var content = null;
    if (routeName) {
        return (<li key="{this.props.key}">
                    <a href={routeName}>{this.props.children}</a>
                </li>)
    } else {
        return (<li key="{this.props.key}">
                    <a>{this.props.children}</a>
                </li>)
    }

}

Now it works. Can anyone point me to why is this?


回答1:


You'll need to drop the quotes when you set properties on the sub-components:

<a href={ routeName }>{ label}</a>

They'll be properly quoted by the React rendering process.



来源:https://stackoverflow.com/questions/28810794/react-not-passing-along-properties-when-rendering-in-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!