props參數傳入:
方法組件, 需要傳入props 參數, 方法內部直接使用props.(不需要this),
class組件, 不需要傳入props 參數, 方法內使用this.props.
官網介紹
(https://www.reactjscn.com/docs/components-and-props.html)
測試模板(正常運行)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--/*1. 選擇使用CDN*/-->
<script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
<script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
<title>React 學習</title>
</head>
<body>
<div id="dd">
</div>
<script type="text/babel">
var divdd = document.getElementById('dd');
//測試函數組件
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
//測試class組件
class NewWelcome extends React.Component{
render(){
return <h1>Hello, {this.props.name}</h1>;
}
}
ReactDOM.render(
<Welcome name="wendel"/>,
divdd
);
</script>
</body>
</html>
result
一, 測試函數組件, 去掉props參數傳遞
function Welcome() {
return <h1>Hello, {props.name}</h1>;
}
// or 下面這種寫法
function Welcome() {
return <h1>Hello, {this.props.name}</h1>;
}
結果直接報錯了.
二, 測試class組件
//測試class組件
class NewWelcome extends React.Component{
render(){
return <h1>Hello, {this.props.name}</h1>;
}
}
運行結果ok
去掉this
//測試class組件
class NewWelcome extends React.Component{
render(){
return <h1>Hello, {props.name}</h1>;
}
}
報錯 Uncaught ReferenceError: props is not defined