React(3)变量使用、变量更新、父子组件变量传递

x33g5p2x  于2022-03-06 转载在 其他  
字(1.7k)|赞(0)|评价(0)|浏览(610)

5、变量

被中括号包含。

  1. let foo = 'world'
  2. class HelloWord extends React.Component {
  3. render() {
  4. return <div className={domClass}>
  5. Hello,{foo}
  6. </div>
  7. }
  8. }

6、组件变量

放在 state 属性中,通过 setState 方法修改.

  1. class HelloWord extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. // 必须存在this.state中
  5. this.state = {
  6. seconds: 0
  7. }
  8. setInterval(() => {
  9. // 调用setState方法修改变量的值
  10. this.setState({
  11. seconds: this.state.seconds + 1
  12. })
  13. }, 1000)
  14. }
  15. render() {
  16. return <div className={domClass}>
  17. Hello,{foo}!距离上一次修改页面,过去了{this.state.seconds}秒
  18. </div>
  19. }
  20. }

7、更新组件变量

将组件变量存到 state 属性中,然后通过 setState() 来更新变量。

  1. class HelloWord extends React.Component {
  2. constructor(props) {
  3. // props的值就是你传给他的变量,比如这里就是 {toChild: 'world'}
  4. super(props);
  5. // 必须存在this.state中
  6. this.state = {
  7. seconds: 0
  8. }
  9. setInterval(() => {
  10. // 调用setState方法修改变量的值
  11. this.setState({
  12. seconds: this.state.seconds + 1
  13. })
  14. }, 1000)
  15. }
  16. render() {
  17. return <div className={domClass}>
  18. {/* 需要通过this.state.world 来使用。当然你也可以赋值到 this 的其他变量 */}
  19. HelloWorld!距离上一次修改页面,过去了{this.state.seconds}秒
  20. </div>
  21. }
  22. }
  23. ReactDOM.render(
  24. <div>
  25. <HelloWord/>
  26. </div>,
  27. document.getElementById('root')
  28. )

8、变量传递

父组件中,通过写在子组件的标签里来传值。

  1. class HelloWord extends React.Component {
  2. constructor(props) {
  3. // props的值就是你传给他的变量,比如这里就是 {toChild: 'world'}
  4. super(props);
  5. // 必须存在this.state中
  6. this.state = {
  7. world: props.toChild,
  8. seconds: 0
  9. }
  10. setInterval(() => {
  11. // 调用setState方法修改变量的值
  12. this.setState({
  13. seconds: this.state.seconds + 1
  14. })
  15. }, 1000)
  16. }
  17. render() {
  18. return <div className={domClass}>
  19. {/* 需要通过this.state.world 来使用。当然你也可以赋值到 this 的其他变量 */}
  20. Hello,{this.state.world}!距离上一次修改页面,过去了{this.state.seconds}秒
  21. </div>
  22. }
  23. }
  24. // 要传的变量
  25. let foo = 'world'
  26. ReactDOM.render(
  27. <div>
  28. {/* ---- toChild 就是传递给子组件的变量的key ---- */}
  29. {/* ---- foo就是被传的变量(这里就是字符串 'world') ---- */}
  30. <HelloWord toChild={foo}/>
  31. <p>当前时间是:{formatDate(new Date())}</p>
  32. {/*<Learner/>*/}
  33. </div>,
  34. document.getElementById('root')
  35. )

相关文章