私のコンポーネントには複数行のtextInputがあり、状態に基づいて初期値を設定します。は、マルチラインtextInputの初期サイズをコンテンツサイズに基づいて設定します。
ラップされたテキストの高さに基づいてフィールドの高さを正しく調整するイベントハンドラを設定しました。onChange
しかし、フィールドに手動で入力するときにのみ呼び出されます。
私はtextFieldから計算されたコンテンツの高さを最初のテキストで取得する方法を理解したいと思います。
class MyComponent extends Component {
_textInput:any;
constructor(props) {
this.handleTextInputChange= this.handleTextInputChange.bind(this)
this.handleLayout= this.handleLayout.bind(this)
this.state.text = "The quick brown fox jumped over the lazy dog"
}
handleTextInputChange(evt){
// This works, but only fires on manual input
const height = Math.max(35, evt.nativeEvent.contentSize.height)
this.setState({text: evt.nativeEvent.text, contentHeight:height})
}
handleLayout(evt){
// I can't seem to get anything useful from this event
}
componentDidMount(){
for (key in this._textInput) console.log(key)
// I can't get anything useful from the
// _textInput object itself either
}
render() {
return(
<TextInput
ref={textInput => (this._textInput = textInput)}
multiline={true}
onChange={this.handleTextInputChange}
onLayout={this.handleLayout}
style={{height: this.state.contentHeight}}
value={this.state.text}
/>
)
}
}
注:RN 0.38同じスタイルプロパティを定期的にText
要素を作り、TextInput
の高さを設定するために、そのonLayout
コールバックを使用することによって解決
ただ、質問に触発されました:なぜあなたは状態の内容の高さを保つでしょう。ここ
は、関連する部分ですか?それはデータの種類の派生ですか?たぶんおそらく(私は細かいことは分かりません)入力の高さを(レンダリング時に)計算することができます。その値を手動で変更した場合や、最初のレンダーや変更が他のものでトリガされた場合は違いはありません方法。あなたには意味がありますか? –RNドキュメントのAutoExpandingTextInputの例から始めました。この例では、高さを格納するためにstateが使用されています。テキストの高さを確実に計算する方法がわかりません。それは、フォントサイズ、重量、文字の幅などに依存します。 textInputコンポーネントのどこかに、onChangeに渡されるnativeEventオブジェクト上にあるため、コンテンツの計算された高さがすでに分かっています。私の問題はonChangeではなく、その高さにアクセスすることです。 –
componentwillmount関数を使用します。ハンドルのTextTextInputChangeをcomponentwillmount関数で呼び出すことができます –