2017-10-19 108 views
0

我試圖根據內容高度來改變textarea的高度。我發現事件處理程序不會更改高度,因爲它被引導程序樣式覆蓋。請幫忙!如何用內容更改textarea的高度?

class PostForm extends React.Component { 
    constructor(props){ 
    super(props); 
    this.state = {titleHeight: '30', storyHeight: 1};              
    this.handleKeyUp = this.handleKeyUp.bind(this); 
    } 
    handleKeyUp(event){ 
    this.setState({titleHeight: document.getElementById('post_title').scrollHeight}); 
    this.setState({storyHeight: document.getElementById('post_story').scrollHeight}); 
    } 
    render() { 
     var csrfToken = $('meta[name=csrf-token]').attr('content'); 
     return (
      <form action='create' method='post' acceptCharset='UTF-8' className= "form-group"> 
      <input type='hidden' name='_method' value='patch'/> 
      <input type='hidden' name='utf8' value='✓' /> 
      <input type='hidden' name='authenticity_token' value={csrfToken} /> 
      <textarea id="post_title" name="post[title]" className="form-control boldText" style={formStyle.textArea} height={this.state.titleHeight} onKeyUp={this.handleKeyUp} placeholder="Title"/> 
      <textarea id="post_story" name="post[story]" className="form-control" style={formStyle.textArea} height={this.state.storyHeight} onKeyUp={this.handleKeyUp} placeholder="Start telling the story"/> 
      <input name="commit" type="submit" value="Post" className="btn" style={formStyle.button}/> 
      </form> 
     ); 
    } 
} 

const formStyle = { 
    textArea: { 
    border: 5, 
    boxShadow: 'none', 
    margin: 5, 
    overflow: 'hidden', 
    resize: 'none', 
    ariaHidden: 'true', 
    }, 
    button: { 
    backgroundColor: 'black', 
    color: 'white', 
    width: 70, 
    marginLeft: 18, 
    marginRight: 5, 
    }, 
} 

回答

2

textarea HTML component有沒有屬性height但屬性rows,您可以使用用於這一目的(例如<textarea rows={Math.round(this.state.storyHeight)} ... />)。

沒有CSS樣式將覆蓋您在style屬性中傳遞的內容,它的工作原理與此相反。但無論如何,您的formStyle定義中沒有height

相關問題