Ba.jsx
import React from 'react';
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
}
setInterval(tick, 1000);
class Clock extends React.Component {
render() {
return (
element
);
}
}
export default Clock;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
//import App from './App.jsx';
// js 组件
import App from './component/js/App.js';
import FormatNameUse from './component/js/FormatName.js';
import GetGreeting from './component/js/GetGreeting.js';
// jsx 组件
import Apa from './component/jsx/Apa.jsx';
import ImgShow from './component/jsx/ImgShow.jsx';
import Clock from './component/jsx/Ba.jsx';
ReactDOM.render(<App name="John"/>,
document.getElementById('app'))
ReactDOM.render(<FormatNameUse name="John"/>,
document.getElementById('app01'))
ReactDOM.render(<GetGreeting />,
document.getElementById('app02'))
ReactDOM.render(<Apa />,
document.getElementById('app03'))
ReactDOM.render(<ImgShow />,
document.getElementById('app04'))
ReactDOM.render(<Clock />,
document.getElementById('app05'))
index.html
<!DOCTYPE html><html>
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id="app"></div>
<div id="app01"></div>
<div id="app02"></div>
<div id="app03"></div>
<div id="app04"></div>
<div id="app05"></div>
<script src="bundle.js"></script>
</body></html>
ClockC.jsx
import React from 'react';
class ClockC extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
tick() {
const nextCount = this.state.count + 1
this.setState({ count: nextCount });
setTimeout(this.tick.bind(this), 1000);
}
render() {
return <div>{this.state.count}</div>;
}
componentDidMount() {
// componentDidMount 组件渲染完成,已经出现在dom文档里
this.tick();
}
}
export default ClockC;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
//import App from './App.jsx';
// js 组件
import App from './component/js/App.js';
import FormatNameUse from './component/js/FormatName.js';
import GetGreeting from './component/js/GetGreeting.js';
// jsx 组件
import Apa from './component/jsx/Apa.jsx';
import ImgShow from './component/jsx/ImgShow.jsx';
import Clock from './component/jsx/Ba.jsx';
import ClockB from './component/jsx/ClockB.jsx';
import ClockC from './component/jsx/ClockC.jsx';
ReactDOM.render(<App name="John"/>,
document.getElementById('app'))
ReactDOM.render(<FormatNameUse name="John"/>,
document.getElementById('app01'))
ReactDOM.render(<GetGreeting />,
document.getElementById('app02'))
ReactDOM.render(<Apa />,
document.getElementById('app03'))
ReactDOM.render(<ImgShow />,
document.getElementById('app04'))
ReactDOM.render(<Clock />,
document.getElementById('app05'))
ReactDOM.render(<ClockB />,
document.getElementById('app06'))
ReactDOM.render(<ClockC />,
document.getElementById('app07'))
依然没有效果
element的变量作用域在tick函数内部,render是无法访问到的。
既然你使用class的语法了,这些逻辑应当写到class中。
我帮你写了个例子