如何使用react进行流畅的文本输入,并根据内容调整大小?

时间:2021-12-10 03:39:24

I'm trying to achieve this functionality: https://paper.fiftythree.com/search

我正在尝试实现此功能:https://paper.fiftythree.com/search

The input box should expand till a max-width based on the content inside. I'm using React by Facebook to do this via state so render gets called automatically.

输入框应根据内部内容扩展到最大宽度。我正在使用React by Facebook通过状态执行此操作,因此渲染会自动调用。

I've put together a small fiddle using span - but couldn't take it through: http://jsfiddle.net/abhinavsingi/3az621c2/

我用跨度放了一个小小提琴 - 但无法通过:http://jsfiddle.net/abhinavsingi/3az621c2/

var Hello = React.createClass({
                getInitialState: function(){
                    return {
                      name: 'hello'
                    };
                },
                render: function() {
                    return (
                        <div className="cont">
                           <span className="spacer-wrap">
                              <span className="spacer">{this.state.name}</span>
                           </span>
                           <input ref='name' id="nm-inp" className="input-wrap" value={this.state.name} onChange={this.onInputChange}/>
                       </div>
                    );
                },

              onInputChange: function(e){
                   console.log(e);
                   this.setState({name: e.currentTarget.value})
              }
           });      React.render(<Hello name="World" />, document.body);

1 个解决方案

#1


1  

Try using style;

尝试使用风格;

    render: function() {
            var nameWidth = this.state.name.length + 'em';
            var spacerSty = {width: nameWidth};
            return (
                    <div className="cont">
                         <span className="spacer-wrap">
                                <span className="spacer" style={spacerSty}>{this.state.name}</span>
                         </span>
                         <input ref='name' id="nm-inp" className="input-wrap" value={this.state.name} onChange={this.onInputChange}/>
                 </div>
            );
    },

#1


1  

Try using style;

尝试使用风格;

    render: function() {
            var nameWidth = this.state.name.length + 'em';
            var spacerSty = {width: nameWidth};
            return (
                    <div className="cont">
                         <span className="spacer-wrap">
                                <span className="spacer" style={spacerSty}>{this.state.name}</span>
                         </span>
                         <input ref='name' id="nm-inp" className="input-wrap" value={this.state.name} onChange={this.onInputChange}/>
                 </div>
            );
    },