ReactJs选择添加默认值 [英] ReactJs Select add default value

查看:202
本文介绍了ReactJs选择添加默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户未在ReactJs中触摸它,我想存储选择默认值.那怎么可能?

I want to store select default value if user not touch it in ReactJs. How is that possible?

<select onChange={this.valSelected.bind(this)}>
    {currencies.map(function(name, index){
        return <option value={name}>{name}</option>;
    })}
</select>

valSelected(event){
    this.setState({
        valSelected: event.target.value
    });
}

推荐答案

您只需将value属性添加到select元素(由您的状态设置)即可.

You can just add a value property to the select element, set by your state.

<select value={this.state.valSelected} onChange={this.valSelected.bind(this)}>
    {currencies.map(function(name, index){
        return <option value={name}>{name}</option>;
    })}
</select>

此处在react docs中进行了描述:文档链接

This is described here in the react docs: Doc Link

然后在构造函数中或使用getInitialState为组件设置默认状态:

Then set a default state for the component, either in the constructor or with getInitialState: What is the difference between using constructor vs getInitialState in React / React Native?

这篇关于ReactJs选择添加默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆