我是编码新手,花了很长时间试图实现这一点,但我被卡住了。我知道这是一个非常基本的问题,如果在其他地方得到答案,我就找不到合适的问题来寻找答案。
这来自react教程——它是一个自动定时器,每1000ms自动更新一次我希望能够将prop
传递到<Clock />
函数调用中,以指定我希望特定对象实例使用的间隔,如下所示:<Clock interval=2000 />
这是他们提供的代码:
function FormattedDate(props) {
return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<FormattedDate date={this.state.date} />
</div>
);
}
}
function App() {
return (
<div>
<Clock />
<Clock />
<Clock />
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
以下是我尝试过的:
- 将状态设置为具有
timer: 5000
- 将其作为
const
传递给函数调用 - 则更新CCD_ 6中的状态
但是,这不起作用,因为我正在尝试使用prop
来更新state
。我该怎么办
未成功的代码:(只是我尝试过的比特(
this.state = {
date: new Date(),
interval: 5000,
};
componentDidMount(props){
() => this.tick(),
props.timer
);
}
const timer = {
interval: 5000,
}
ReactDOM.render()
<Clock interval={timer.interval}/>,
document.getElementById('root')
);
如果你想把间隔作为道具传递,你可以这样做:
<Clock interval="1000"/>
并像这样访问它:
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
this.props.interval
);
}
您必须使用this.props
才能访问类组件中的道具。