state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据。
demo1
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>菜鸟教程 React 实例</title> <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script> <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script> <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="example"></div> <div id = "helloReactZzw"></div> <script type="text/babel"> function HelloMessage(props) { return <h1>Hello {props.name}!</h1>; } class HelloMessageZzw extends React.Component { render() { return ( <h1>Hello, {this.props.myname}</h1> ); } } const element = <HelloMessage name="Runoob"/>; const elementZzw = <HelloMessageZzw myname = "zzwLearningReact"/>; //const elementZzw1 = <HelloMessageZzw myname = "zzwLearningReact"/> + <HelloMessage name="Runoob"/>; //留一下一个问题下次思考 ReactDOM.render( elementZzw, document.getElementById(‘example‘) ); </script> </body> </html>
demo2
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>菜鸟教程 React 实例</title> <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script> <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script> <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="example"></div> <div id = "helloZzw"/> <script type="text/babel"> class HelloMessage extends React.Component { render() { return ( <h1>Hello, {this.props.myname}</h1> ); } } HelloMessage.defaultProps = { name: ‘Runoob‘, myname:‘zzw‘, }; const element = <HelloMessage/>; ReactDOM.render( element, document.getElementById(‘helloZzw‘) ); </script> </body> </html>
原文地址:https://www.cnblogs.com/zzzzw/p/10462235.html
时间: 2024-10-08 09:37:55