我有一个输入、文本和按钮组件。我想在单击按钮时用输入值更改文本值。我在stackoverflow上搜索,但它们只在使用textinput的onChangeText属性更改输入文本后才更改文本。
4zcjmb1e1#
用途按下按钮组件的prop。此prop接受单击按钮时将调用的函数。在该函数中,可以使用setState方法用输入的新文本值更新组件的状态,这将触发组件的重新呈现并更新文本值。
class MyComponent extends React.Component { constructor(props) { super(props); this.state = { textValue: '', }; } onButtonPress = () => { const { inputValue } = this.state; this.setState({ textValue: inputValue, }); } render() { const { textValue } = this.state; return ( <View> <TextInput value={inputValue} onChangeText={inputValue => this.setState({ inputValue })} /> <Button onPress={this.onButtonPress} title="Update Text" /> <Text>{textValue}</Text> </View> ); } }
onButtonPress函数在单击按钮时被调用,它使用当前的inputValue更新textValue状态,这将使用分配的新值更新文本。
xytpbqjk2#
若要在单击Button时根据Input组件得值更改文本组件得文本值,可以使用Button组件得onPress属性定义一个事件处理函数,该事件处理函数用于更新文本组件得文本值.下面是一个示例 (注:只是一个示例-您没有提供代码,我可以根据它) 如何做到这一点:
Button
onPress
import React from 'react'; import { Button, Input, Text } from 'react-native'; class MyApp extends React.Component { constructor(props) { super(props); this.state = { inputValue: '', textValue: '', }; } handleInputChange = (inputValue) => { this.setState({ inputValue }); } handleButtonPress = () => { this.setState({ textValue: this.state.inputValue }); } render() { return ( <> <Input value={this.state.inputValue} onChangeText={this.handleInputChange} /> <Button title="Update text" onPress={this.handleButtonPress} /> <Text>{this.state.textValue}</Text> </> ); } }
在此示例中,MyApp组件维护输入值和文本值的状态。当Input组件的值更改时,将调用handleInputChange事件处理程序,并更新组件状态中的输入值。当按下Button时,将调用handleButtonPress事件处理程序。并使用当前输入值更新组件状态中的文本值。最后,使用组件状态中的当前文本值呈现文本组件。通过使用onChangeText与onPress属性定义更新组件状态得事件处理程序,可以根据Input组件得值控制Text组件得文本值.
MyApp
handleInputChange
handleButtonPress
onChangeText
2条答案
按热度按时间4zcjmb1e1#
用途
按下
按钮组件的prop。此prop接受单击按钮时将调用的函数。
在该函数中,可以使用setState方法用输入的新文本值更新组件的状态,这将触发组件的重新呈现并更新文本值。
onButtonPress函数在单击按钮时被调用,它使用当前的inputValue更新textValue状态,这将使用分配的新值更新文本。
xytpbqjk2#
若要在单击Button时根据Input组件得值更改文本组件得文本值,可以使用
Button
组件得onPress
属性定义一个事件处理函数,该事件处理函数用于更新文本组件得文本值.下面是一个示例 (注:只是一个示例-您没有提供代码,我可以根据它) 如何做到这一点:
在此示例中,
MyApp
组件维护输入值和文本值的状态。当Input组件的值更改时,将调用handleInputChange
事件处理程序,并更新组件状态中的输入值。当按下Button
时,将调用handleButtonPress
事件处理程序。并使用当前输入值更新组件状态中的文本值。最后,使用组件状态中的当前文本值呈现文本组件。通过使用
onChangeText
与onPress
属性定义更新组件状态得事件处理程序,可以根据Input组件得值控制Text组件得文本值.