如何用内容改变textarea的高度?

问题描述 投票:0回答:2

我试图根据内容高度更改textarea的高度。我发现事件处理程序不会改变高度,因为它被bootstrap样式覆盖。请帮忙!

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,
  },
}
reactjs ecmascript-6 jsx react-rails
2个回答
3
投票

textarea HTML component没有属性height,但你可以用于此目的的属性rows(例如<textarea rows={Math.round(this.state.storyHeight)} ... />)。

没有CSS样式会覆盖你在style属性中传递的内容,它的工作方式相反。但无论如何,你的height定义中没有formStyle


0
投票

你可以用ref属性做你想做的事

export default class Textarea extends Component {

  componentDidMount () {
    if (this.multilineTextarea) {
      this.multilineTextarea.style.height = 'auto';
    }
  }

  changeTextarea = () => {
    this.multilineTextarea.style.height = 'auto';
    this.multilineTextarea.style.height = this.multilineTextarea.scrollHeight + 'px';
  }

  render () {
    return (
      <textarea
        onChange={this.changeTextarea}
        ref={ref => this.multilineTextarea = ref}
      />
    );
  }
}

Also here is working DEMO

© www.soinside.com 2019 - 2024. All rights reserved.