Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

reactjs - React js set state in functional component

I am trying to create a functional login component. When i have commented the onChange i get the below error in the browser

index.js:1 Warning: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.

And if i uncomment onChange and i try to username field i get the below error Login.js:20 Uncaught TypeError: Cannot read property 'inputChangedHandler' of undefined at onChange (Login.js:20)

How to solve it? import React, { useState, props } from 'react';

const Login = (prop) => {

    const [username] = useState('Mr x');


    const inputChangedHandler = (event) => {
        const updatedKeyword = event.target.value;
        // May be call for search result
    }


    return (
        <div>
            <h1>Login</h1>
            <div className="container">

                User Name: <input type="text" name="username" value={username}
                  //  onChange={(event) => this.inputChangedHandler(event)}
                     />

                    Password: <input type="password" name="password" />
                <button className="btn btn-success"  >Login</button>
            </div>
        </div>
    )
}


export default Login;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to remove the this from this.inputChangedHandler(event)

And to actually change the value you need to add a setter to your useState like this const [username,setUsername] = useState('Rahul Raj');

And then use it like this onChange={(event) => setUsername(event.target.value)}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...