在React JSX中,似乎不可能这样做:
render: function() {
return (
<{this.props.component.slug} className='text'>
{this.props.component.value}
</{this.props.component.slug}>
);
}
我收到解析错误:意外的令牌{.这是不是React可以处理的东西?
我正在设计这个组件,以便在幕后,存储在this.props.component.slug
中的值将包含有效的HTML元素(h1、p等)。有没有办法让这件事起作用呢?
发布于 2014-10-23 14:22:36
不应将组件slug放在大括号中:
var Hello = React.createClass({
render: function() {
return <this.props.component.slug className='text'>
{this.props.component.value}
</this.props.component.slug>;
}
});
React.renderComponent(<Hello component={{slug:React.DOM.div, value:'This is my header'}} />, document.body);
这是一个有用的小提琴:http://jsfiddle.net/kb3gN/6668/
此外,您还可以发现JSX Compiler对调试这类错误很有帮助:http://facebook.github.io/react/jsx-compiler.html
发布于 2015-06-02 16:43:36
正如尼尔冈之前指出的那样,组件段塞不应该用大括号括起来。
如果您决定将其存储在变量中,请确保它以大写字母开头。
下面是一个示例:
var Home = React.createClass({
render: function() {
return (
<div>
<h3>This is an input</h3>
<CustomComponent inputType="input" />
<h3>This is a text area</h3>
<CustomComponent inputType="textarea" />
</div>
);
}
});
var CustomComponent = React.createClass({
render: function() {
// make sure this var starts with a capital letter
var InputType = this.props.inputType;
return <InputType />;
}
});
React.render(<Home />, document.getElementById('container'));
这里有一个有效的工具:https://jsfiddle.net/janklimo/yc3qcd0u/
发布于 2015-11-04 02:43:05
如果你的意图是注入实际呈现的组件,你可以这样做,这对于测试非常方便,或者任何你想要动态注入组件来呈现的原因。
var MyComponentF=function(ChildComponent){
var MyComponent = React.createClass({
getInitialState: function () {
return {
};
},
componentDidMount: function () {
},
render: function () {
return (
<div className="MyComponent">
<ChildComponent></ChildComponent>
</div>
);
}
});
return MyComponent;
};
var OtherComponentF=function(){
var OtherComponent = React.createClass({
getInitialState: function () {
return {
};
},
componentDidMount: function () {
},
render: function () {
return (
<div className="OtherComponent">
OtherComponent
</div>
);
}
});
return OtherComponent;
};
var AnotherComponentF=function(){
var AnotherComponent = React.createClass({
getInitialState: function () {
return {
};
},
componentDidMount: function () {
},
render: function () {
return (
<div className="AnotherComponent">
AnotherComponent
</div>
);
}
});
return AnotherComponent;
};
$(document).ready(function () {
var appComponent = MyComponentF(OtherComponentF());
// OR
var appComponent = MyComponentF(AnotherComponentF());
// Results will differ depending on injected component.
ReactDOM.render(React.createElement(appComponent), document.getElementById("app-container"));
});
https://stackoverflow.com/questions/26518629
复制相似问题