老舊專案改造使用react 普通頁面使用react.js和sass
阿新 • • 發佈:2020-12-25
技術標籤:js/jquery學習經驗html學習經驗react
react參考:https://www.cnblogs.com/lyraLee/p/11885487.html
sass參考:https://www.cnblogs.com/wuqilang/p/13371176.html(vscode安裝live sass compiler和live server)
直接在頁面中使用react.js
- 專案結構
- html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=" UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 載入 React。-->
<!-- 注意: 部署時,將 "development.js" 替換為 "production.min.js"。-->
<script src="./js/react.development.js" crossorigin></script>
<script src="./js/react-dom.development.js" crossorigin></script>
<script src="./js/babel.min.js"></script>
<!-- 編譯好的style.css -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>參看:https://www.cnblogs.com/lyraLee/p/11885487.html</div>
<div id="like_button_container"></div>
<div id="root"></div>
<!-- 載入我們的 React 元件。-->
<script src="like_button.js"></script>
<script type="text/babel">
//有狀態元件
class MButton extends React.Component {
constructor(props) {
super(props)
this.state = { liked: false }
}
render() {
if (this.state.liked) {
return "you liked";
}
return (
<div>
<h5 style={{ color: 'red' }}>Hello, {this.props.name}</h5>
{/**<button onClick={this.setState({like:true})}>like</button>**/}
<button onClick={() => this.setState({ liked: true })}>Like</button>
</div>
);
}
}
//無狀態元件
function Welcome(props) {
return <h5>Hello, {props.name}</h5>;
}
//組合
function PostHeader(props) {
return <h3 className={'title'}>{props.title}</h3>
}
function PostBody(props) {
return (
<div>
<p className={'content'}>{props.content}</p>
</div>
)
}
class Post extends React.Component {
constructor(props) {
super(props)
this.state = {}
}
render() {
return (
<div>
<PostHeader title={this.props.post.title} />
<PostBody content={this.props.post.content} />
</div>
)
}
}
</script>
<script type="text/babel">
const posts = [
{ id: 1, title: 'post1', content: 'content1' },
{ id: 2, title: 'post2', content: 'content2' },
{ id: 3, title: 'post3', content: 'content3' },
{ id: 4, title: 'post4', content: 'content4' },
{ id: 5, title: 'post5', content: 'content5' },
]
ReactDOM.render(
(<div>
<h5>home</h5>
<MButton name='La❤' />
<Welcome name='Ali' />
{/**單個演示**/}
<Post post={posts[0]} />
{/**列表演示**/}
{posts.map(item => {
return <Post post={item} key={item.id}/>
})}
</div>),
document.getElementById('root')
);
</script>
</body>
</html>
- js
//like_button.js
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
- scss
div{
.title{
color:red
}
.content{
color:peru;
}
}