简体   繁体   English

通过反应调整文本区域高度

[英]Adjust textarea height with react

I'm trying to make a dynamically adjust height to my textarea.我正在尝试对我的文本区域进行动态调整高度。 I saw here some solution but it's now work for me.. my code:我在这里看到了一些解决方案,但它现在对我有用.. 我的代码:

const textArea = document.querySelector("textarea");
const textRowCount = textArea ? textArea.value.split("\n").length : 1;
const rows = textRowCount;

<textarea type="text" className="chat-box" rows={rows} style={{ height: "unset" }} />

css: css:

.chat-box{
    width: 70%;
    border-radius: 25px;
    border: solid 1px #b7b7b7;
    background-color: #eeeeee;
    margin-left: 2%;
    padding-left: 3%;
    padding-right: 3%;
    padding-top: 2%;
    padding-bottom: 2%;
    margin-top:0.5%;
    resize: none;
    vertical-align: middle;
    overflow: hidden;
}
.chat-box:focus{
    outline-style: none;
}
.chat-box::-webkit-scrollbar {
    width: 2px;
}
.chat-box::-webkit-scrollbar-track {
    background: #eeeeee; 
    border-left: solid 1px #b6bcca;
    width: 10px;
}
.chat-box::-webkit-scrollbar-thumb {
    background: #7b808b;
    border-radius: 3px;   
}

I want that by press "Enter" the rextarea will be one more line (and if it is possible to make it bigger to the top it will be great - just like in whatsapp computer app.我希望通过按“Enter”,rextarea 将再增加一行(如果可以将其扩大到顶部,那就太好了 - 就像在 whatsapp 计算机应用程序中一样。

You have to use controlled components and also put this value in state:您必须使用受控组件并将此值放入 state:

const textRowCount = textArea ? textArea.value.split("\n").length : 1;

The updated value will not be passed to the textbox until the contents and the rowCount are stored in state.在内容和rowCount存储在 state 之前,更新的值不会传递到文本框。 A quick example would be:一个简单的例子是:

function App() {
  const [value, setValue] = useState("");
  const rows = value.split("\n").length;
  return (
    <div className="App">
      <textarea
        value={value}
        rows={rows}
        onChange={(e) => setValue(e.target.value)}
      />
    </div>
  );
}

Live Snippet实时片段

 textarea {resize: none; width: 500px;}
 <div id="root"></div> <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script> <script type="text/babel"> function App() { const [value, setValue] = React.useState(""); const rows = value.split("\n").length; return ( <div className="App"> <textarea value={value} rows={rows} onChange={(e) => setValue(e.target.value)} /> </div> ); } ReactDOM.render( <App />, document.getElementById('root') ); </script>

Preview预习

预习

Check out demo: CodeSandbox查看演示: CodeSandbox

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM