[email protected]’s Humble Abode       博  客   时 间 线   归  档 



React
Published on Fri Sep 17 2021 12:00:01 GMT+0000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function Hello(props) {
return <div>Hello,{props.name}</div>
}

let elementList = [];
for (let i = 0;i<3;i++){
elementList.push(<Hello name={i}/>);
}

let element = <div>{elementList}</div>

function Time(props){
let now = new Date();
now = now.toLocaleTimeString();
return <div>{now}</div>;
}

ReactDOM.render(element,document.getElementById('root'));
ReactDOM.render(<Time/>,document.getElementById('time'));

function tick() {
const element = <Time/>
ReactDOM.render(element, document.getElementById('time'));
}

var interval = setInterval(tick, 1000);

定义一个组件类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>

);
}
}

ReactDOM.render(
<Clock />,
document.getElementById('root')
);