Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[react] 如何给非控组件设置默认的值? #894

Open
haizhilin2013 opened this issue Jul 16, 2019 · 5 comments
Open

[react] 如何给非控组件设置默认的值? #894

haizhilin2013 opened this issue Jul 16, 2019 · 5 comments
Labels
react react

Comments

@haizhilin2013
Copy link
Collaborator

[react] 如何给非控组件设置默认的值?

@haizhilin2013 haizhilin2013 added the react react label Jul 16, 2019
@jiangbo2015
Copy link

<input defaultValue="123" />

@idododu
Copy link

idododu commented Feb 25, 2020

  • 表单元素依赖于状态(state),表单元素需要默认值实时映射到状态的时候,就是受控组件
<input name="username" type="text" value={this.state.username} onChange={this.handleChange} />
  • 不通过state控制表单元素,而是通过ref来控制的表单元素就是非受控组件
<input name="username" type="text" ref={username=>this.username=username}/>

@UserRegistering
Copy link

给组件设置默认值,难道就没人说static defaultProps吗?

@liuyingbin19222
Copy link

可在state设置默认值;

@daryl-lau
Copy link

daryl-lau commented Aug 12, 2020

给非受控组件设置defaultValue属性,给定默认值
官方文档

示例代码:

import React from 'react'

export default class UnControlledComp extends React.Component {
  constructor(props) {
    super(props)
    this.inputRef = React.createRef()
  }

  handleClick = () => {
    console.log(this.inputRef.current.value);
  }

  render () {
    return (
      <>
        <input defaultValue="default value" ref={this.inputRef}></input>
        <button onClick={this.handleClick}>点击</button>
      </>
    )
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
react react
Projects
None yet
Development

No branches or pull requests

6 participants