首页 > 解决方案 > 无法显示 Formik 表单

问题描述

我正在尝试显示我的 formik 表单,这是我第一次使用它。然而,屏幕是完全空白的。我认为这与我的风格有关,但我不确定。这是我的代码:

export default class Checkout extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Formik
          initialValues={{first_name: '', last_name: ''}}
          onSubmit={(values) => {
            console.log(values);
          }}>
          {(props) => {
            <View>
              <TextInput
                style={styles.input}
                placeholder="first name"
                onChangeText={props.handleChange('first_name')}
                value={props.values.first_name}
              />
              <TextInput
                style={styles.input}
                placeholder="last name"
                onChangeText={props.handleChange('last_name')}
                value={props.values.last_name}
              />
              <Button
                title="place order"
                color="maroon"
                onPress={props.handleSubmit}
              />
            </View>;
          }}
        </Formik>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  input: {
    borderWidth: 1,
    borderColor: 'black',
    padding: 10,
    fontSize: 18,
    borderRadius: 6,
  },
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

标签: javascriptformsreact-nativeformik

解决方案


由于您使用的是 {} 那么您应该返回类似这样的内容


<Formik
          initialValues={{first_name: '', last_name: ''}}
          onSubmit={(values) => {
            console.log(values);
          }}>
          {(props) => {return (<View ...} }

或者您可以在 Formik 中删除这些 {},然后无需键入 return 语句,因为您只返回一件事。这是你应该做的

export default class Checkout extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Formik
          initialValues={{first_name: '', last_name: ''}}
          onSubmit={(values) => {
            console.log(values);
          }}>
          {(props) => 
            <View>
              <TextInput
                style={styles.input}
                placeholder="first name"
                onChangeText={props.handleChange('first_name')}
                value={props.values.first_name}
              />
              <TextInput
                style={styles.input}
                placeholder="last name"
                onChangeText={props.handleChange('last_name')}
                value={props.values.last_name}
              />
              <Button
                title="place order"
                color="maroon"
                onPress={props.handleSubmit}
              />
            </View>;
          }
        </Formik>
      </View>
    );
  }
}

推荐阅读