2015-11-26 24 views
3

需要使用react和参数属性为标题(&女士)创建单选按钮。在React中使用参考创建单选按钮

规范类(省略无用的部分): -

getTitle() { 
// how could I get the selected title value here 
var title = this.refs. ??; 
}, 

render() { 
    return (
     <div className='input-wrap'> 
         <label className='label'> 
          Mr. 
         </label> 
         <input className='input' 
           type='radio' 
           ref= 'title' 
           name='user_title' 
           value='Mr.' 
           selected /> 

         <label className='label'> 
          Ms. 
         </label> 
         <input className=input' 
           type='radio' 
           ref= 'title' 
           name='user_title' 
           value='Ms.' /> 
        </div> 

    ) 
    } 

问题: -我怎么能在getTitl获得所选择的标题值 E()?

回答

4

你可以不用refs

class Radio extends React.Component{ 
    constructor(){ 
     super(); 
     this.state = { 
      inputValue : '' 
     } 

    } 

    change(e){ 
     const val = e.target.value; 
     this.setState({ 
      inputValue : val 
     }) 
    } 
    render(){ 
     return <div> 
       <label>MR<input type="radio" name="name" onChange={this.change.bind(this)} value="MR"/></label> 
       <label>MS<input type="radio" name="name" onChange={this.change.bind(this)} value="MS"/></label> 
       <br/> 
       <h2>Value : {this.state.inputValue}</h2> 
     </div> 
    } 
} 

React.render(<Radio/>, document.getElementById('container')) 

Fiddle example is here

我希望它会帮助你的!

谢谢!