Javascript 在react类中:如何在同一组件内传递变量
我正在学习ReactJS,需要在同一个组件中传递一个变量 这里有一个例子Javascript 在react类中:如何在同一组件内传递变量,javascript,reactjs,Javascript,Reactjs,我正在学习ReactJS,需要在同一个组件中传递一个变量 这里有一个例子 var DataBase = [ { position: 1 }, { position: 2 }, { position: 3 }, { position: 4 } ]; var Component = React.createClass({ getDefaultProps: fun
var DataBase = [
{
position: 1
},
{
position: 2
},
{
position: 3
},
{
position: 4
}
];
var Component = React.createClass({
getDefaultProps: function() {
var counter = 0;
},
componentDidMount: function() {
var dbPos = this.props.db[counter+1].position;
return dbPos;
},
render: function () {
return (
<div className="Component">
{this.dbPos}
</div>
);
}
});
ReactDOM.render(
<Component db={DataBase} />,
document.getElementById('main')
);
var数据库=[
{
职位:1
},
{
职位:2
},
{
职位:3
},
{
职位:4
}
];
var Component=React.createClass({
getDefaultProps:function(){
var计数器=0;
},
componentDidMount:function(){
var dbPos=this.props.db[counter+1]。位置;
返回dbPos;
},
渲染:函数(){
返回(
{this.dbPos}
);
}
});
ReactDOM.render(
,
document.getElementById('main')
);
所以,这显然不起作用。我需要的是将在componentDidMount
中创建的var dbPos
传递到render
(没有像onClick这样的任何事件)。这将是时间驱动的,例如使用setTimeout()在每个位置上10秒
这可能吗?怎么用?有更好的解决办法吗?我将感谢您的帮助。这个问题可能与国家处理有关。在React应用程序中,有多种方法可以处理应用程序的状态,但我假设您有兴趣将dbPos
作为组件状态的一部分(将来可能会对其进行修改)。要实现这一点,只需使用this.setState
和this.state
在展示示例之前,我将陈述代码片段中的一些其他错误:
应该返回props的哈希对象,而不是用var声明它们(这将使它们的作用域限定在方法而不是组件实例上)getDefaultProps
作为道具,必须称为计数器
。请注意,此.props.counter
不是此组件状态的一部分,并且只能随组件树上层中该属性的相应更改而更改李>计数器
var Component = React.createClass({
getDefaultProps: function() {
return {counter: 0};
},
componentDidMount: function() {
var dbPos = this.props.db[this.props.counter+1].position;
this.setState({ // change the state of this component
dbPos: dbPos
})
},
render: function () {
return (
<div className="Component">
{this.state.dbPos}
</div>
);
}
});
这一问题可能与国家处理有关。在React应用程序中,有多种方法可以处理应用程序的状态,但我假设您有兴趣将dbPos
作为组件状态的一部分(将来可能会对其进行修改)。要实现这一点,只需使用this.setState
和this.state
在展示示例之前,我将陈述代码片段中的一些其他错误:
应该返回props的哈希对象,而不是用var声明它们(这将使它们的作用域限定在方法而不是组件实例上)getDefaultProps
作为道具,必须称为计数器
。请注意,此.props.counter
不是此组件状态的一部分,并且只能随组件树上层中该属性的相应更改而更改李>计数器
var Component = React.createClass({
getDefaultProps: function() {
return {counter: 0};
},
componentDidMount: function() {
var dbPos = this.props.db[this.props.counter+1].position;
this.setState({ // change the state of this component
dbPos: dbPos
})
},
render: function () {
return (
<div className="Component">
{this.state.dbPos}
</div>
);
}
});
您可以将变量附加到
this
,或者使用类似getDbPosition
的方法。您可以将变量附加到this
,或者使用类似getDbPosition
的方法,但该方法不起作用。控制台返回(this.state为null)编辑:是的,使用第二种方法它可以工作!:)谢谢那没用。控制台返回(this.state为null)编辑:是的,使用第二种方法它可以工作!:)谢谢