在JSX中只要看到 {}
就会当做JS来解析(执行里面的JS代码),所以无论是绑定属性, 还是绑定类名, 还是绑定样式, 只需要将字符串改为 {}
然后再通过JS动态获取, 动态绑定即可,对于普通属性而言, 过去怎么绑定, 现在就怎么绑定,以下将会给出一些案例,和测试的效果图,如下所示。
绑定普通属性
<p title="我是标题">我是段落</p>
<p title={message}>我是段落</p>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./react.development.v17.js"></script>
<script src="./react-dom.development.v17.js"></script>
<script src="./babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
class Home extends React.Component {
constructor() {
super();
this.state = {
message: 'BNTang'
}
}
render() {
return (
<div>
<p id="box">{this.state.message}</p>
<p title={this.state.message}>{this.state.message}</p>
</div>
)
}
}
ReactDOM.render(<Home/>, document.getElementById('app'));
</script>
</body>
</html>
绑定类名 (class)
由于JSX本质是转换成JS代码, 而在JS中 class 有特殊含义, 所以不能使用,同理可证, 但凡是属性名称是JS关键字的都不能直接使用。
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./react.development.v17.js"></script>
<script src="./react-dom.development.v17.js"></script>
<script src="./babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
class Home extends React.Component {
constructor() {
super();
this.state = {
message: 'BNTang'
}
}
render() {
return (
<div>
<p className="active">{this.state.message}</p>
</div>
)
}
}
ReactDOM.render(<Home/>, document.getElementById('app'));
</script>
</body>
</html>
绑定样式 (style)
由于样式是键值对形式的, 所以在JSX中如果想要动态绑定样式,必须将样式放到一个对象中, 并且所有以 -
连接的样式名称都要转换成驼峰命名的形式,
<p style={{color:'red', fontSize:'50px'}}>绑定样式</p>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./react.development.v17.js"></script>
<script src="./react-dom.development.v17.js"></script>
<script src="./babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
class Home extends React.Component {
constructor() {
super();
this.state = {
message: 'BNTang'
}
}
render() {
return (
<div>
<p style={{color: 'red', fontSize: '100px'}}>{this.state.message}</p>
</div>
)
}
}
ReactDOM.render(<Home/>, document.getElementById('app'));
</script>
</body>
</html>