简体   繁体   中英

How to get value of a function in defaultValue attribute of an InputBox in ReactJS

I want my defaultValue attribute of an input box to be bound by a reactive function.

getSelectedColor(e) {
    return 'red'; // just for sake of simplicity now
}

and here is my virtual DOM (HTML) defined inside the render() function

<input type="text" defaultValue={this.getSelectedColor.bind(this)} />

I have declared the function inside the constructor of the component class.

The result of the above implementation is my input box showing value function () { [native code] }

This happens even if I write inline function for defaultValue attribute

<input type="text" defaultValue={()=>{return 'red'}} />

How to get the value returned from the function?

You want to assign the value to defaultValue attribute, so instead of binding the method call that method, like this:

<input type="text" defaultValue={this.getSelectedColor()} />

Binding is not required here.

Note:

defaultValue: this will assign the initial value only, means one time during the initial rendering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM