渲染TextInput提交 - React Native

时间:2017-07-10 02:14:38

标签: javascript react-native react-native-ios

在一个本机应用程序中,我有一些文本,然后在屏幕上呈现文本输入。我在原始文本字段中提交时试图弄清楚如何输出相同的文本和相同的textinput。我想以递归的方式做这件事,但我不知道在何处以及如何实现这个功能。

2 个答案:

答案 0 :(得分:0)

如果它在同一个屏幕上,则可以使用本地状态。这是示例

class TestScreen extends Component {
  constructor(props) {
    super(props)
    this. state = { 
      firstInput:'First Input',
      secondInput:''
    }
    this.submit = this.submit.bind(this)
  }

  submit(){
    this.setState({ secondInput: this.state.firstInput })
  }


  render() {
    return (
      <View style={{flex:1,marginTop:40}}>

        <View>
          <Text>Text Input #1</Text>
          <TextInput  
             style={{height: 40, borderColor: 'gray', borderWidth: 1}} 
             onChangeText={(text)=> this.setState({firstText:text})}
             value={this.state.firstInput}
            />
            <Button 
              onPress={this.submit}
              title="Submit"
            />
        </View>

        <View style={{marginTop:20}}>
          <Text>Text Input #1</Text>
          <TextInput 
          style={{height: 40, borderColor: 'gray', borderWidth: 1}}
          value={this.state.secondInput}
          />
        </View>
      </View>
    );
  }
}

我希望有所帮助。感谢

答案 1 :(得分:0)

Perhap你可以使用ref,state,conditional rendering。让我们的代码谈谈

const MyInputs = (props) => {
  inputs =props.inputs
  result=inputs.map(function(value,index){
    return(
      <TextInput key={index} style={styles.input} value={value} />
    )  
  })

  return(
    <View>
      {result}
    </View>
  )
}


class TestScreen extends Component {
  constructor(props) {
    super(props)
    this. state = { 
      inputs:[]  
    }
    this.submit = this.submit.bind(this)
    this.clearText = this.clearText.bind(this)
  }

  submit(){
    let lastInput=this._textInput._lastNativeText
    let inputs=this.state.inputs
    this._textInput.setNativeProps({text: ''});
    inputs.push(lastInput)
     this.setState({ 
      inputs:inputs
    })
  }

  clearText = () => {
    this.setState({ 
      inputCount: this.state.inputCount + 1,
    })
    this._textInput.setNativeProps({text: ''});
  }

  render() {
    return (
      <View style={{flex:1,marginTop:40}}>
        <View>
          <Text>Text Input #1</Text>
          <TextInput  
             style={styles.input} 
             ref={component => this._textInput = component}
          />
          <Button onPress={this.submit} title="Submit"
          />
        </View>

        <MyInputs inputs={this.state.inputs}/>
      </View>
    );
  }
}