bgm*_*ter 20 javascript reactjs meteor-react
我是使用react.js的新手,我正在尝试编写一个可重用的组件,该组件具有传递给它的可选属性.在组件中,该可选属性使用meteor从db中提取数据,然后我想检查返回对象上是否存在属性(任务中是否存在parent_task),如果存在,则添加链接.这似乎相当简单,但我一直在收到错误.有没有人对我可能缺少什么有任何建议?我缺少一个jsx陷阱吗?
<Header task={params.task_id} /> // rendering component with property
// Task List Header
Header = React.createClass({
mixins: [ReactMeteorData],
getMeteorData() {
var handle = Meteor.subscribe('tasks');
return {
taskLoading: ! handle.ready(),
task: Tasks.findOne({_id: this.props.task})
}
},
getParentTaskLink() {
if (!this.data.taskLoading) {
var current_task = this.data.task;
if (parent_task in current_task) { // or current_task.hasOwnProperty(parent_task)
console.log("parent_task exists!");
}
}
},
render() {
return (
<div className="bar bar-header bar-calm">
{this.getParentTaskLink()} // eventually return anchor element here
<h1 className="title">Hello World</h1>
</div>
)
}
});
Run Code Online (Sandbox Code Playgroud)
met*_*eta 29
有问题的道具是什么?怎么样
{this.props.propInQuestion ? <a href="#">link</a> : null}
Run Code Online (Sandbox Code Playgroud)
小智 10
对我来说有效:
if ('myProperty' in this.props) {}
Run Code Online (Sandbox Code Playgroud)
或者
if (this.props.myProperty !== undefined) {}
Run Code Online (Sandbox Code Playgroud)
或者
if (this.props.hasOwnProperty('myProperty')) {}
Run Code Online (Sandbox Code Playgroud)
下一个条件不适用于 number 属性,因为 0 值不起作用(例如空字符串):
if (this.props.MaxValue) {}
Run Code Online (Sandbox Code Playgroud)
我想通了.显然这是一个语法问题 - 在搜索对象中的属性时需要使用字符串.以下行有效:
if ('parent_task' in current_task)
Run Code Online (Sandbox Code Playgroud)
使用 React.js 检查属性是否存在
您可以使用两个选项。&& 运算符和 If 语句来检查道具是否存在。选项 1 将检查该属性是否存在,然后运行代码的第二部分。它就像没有 if 的 if 一样。
选项1
this.props.property && this.props.property
Run Code Online (Sandbox Code Playgroud)
选项 2
if(this.props.property){
this.props.property
}
Run Code Online (Sandbox Code Playgroud)
这也适用于函数名称。
您也可以使用此检查来呈现组件和标签。
| 归档时间: |
|
| 查看次数: |
46221 次 |
| 最近记录: |