2017-02-13 37 views
-2

我想我并不了解ReactJS的概念。我想我可以用它写“自定义标签”。例如,我可以做一个输入字段,有一些额外的功能,让我如下可以使用它: -html中的React组件

<form id="theForm"> 
    <input type="text" /> 
    <input type="text" /> 

    <my-input-field /> 
    <my-input-field /> 
    <my-input-field /> 

    <input type="submit" /> 
</form> 

据我了解,我必须通过“theForm”我的分量呈现完整形式,对吧?自定义标签只允许在JSX渲染函数中使用?

如果我想在一个页面上有很多组件,我必须为每个元素调用ReactDOM.render()方法?像这样:

HTML:

<form id="theForm"> 
    <input type="text" /> 
    <input type="text" /> 

    <input id="custom-1" /> 
    <input id="custom-2" /> 
    <input id="custom-3" /> 

    <input type="submit" /> 
</form> 

JS:

ReactDOM.render(<my-input-field />, document.getElementById("custom-1")); 
ReactDOM.render(<my-input-field />, document.getElementById("custom-2")); 
ReactDOM.render(<my-input-field />, document.getElementById("custom-3")); 

非常感谢!

+1

自定义组件必须大写,否则将被视为DOM元素 – Li357

+2

我想你可能需要再看一遍文档。你将会把你的主/根组件渲染成一个块元素(在教程中通常是一个id为“app”的div)。您的子组件(可以包含表单,段落,列表等)将在父组件中呈现。你需要思考模块化。 React有一个很好的[教程](https://facebook.github.io/react/tutorial/tutorial.html)。 – Jecoms

+0

在您重新阅读本教程时,请记住,该模式仅对您的根元素使用ReactDOM.render一次。然后从那里构建你的子元素,通常使用'map'来重复元素。 – jmargolisvt

回答

0

我想我找到了我想要的 - 同一个组件在一个页面中多次。在我的例子中,我有一个自定义输入字段,但我不希望整个表单是一个组件。

HTML:

 <form> 
      <input type="text" name=""> 
      <div class="my-input-field" data-myprop="First" ></div> 
      <input type="text" name=""> 
      <input type="text" name=""> 
      <div class="my-input-field" data-myprop="Second" ></div> 
      <input type="text" name=""> 
      <div class="my-input-field" data-myprop="Third" ></div> 
      <input type="submit"> 
     </form> 

index.tsx:

import * as React from "react"; 
import * as ReactDOM from "react-dom"; 

import { MyInputField } from "./components/MyInputField"; 

let myInputFields = Array.prototype.slice.call(document.getElementsByClassName("my-input-field")); 
for (let element of myInputFields) { 
    ReactDOM.render(<MyInputField myprop={element.dataset.myprop} />, element) 
} 

MyInputField.tsx

import * as React from "react"; 

export interface MyInputFieldProps { 
    myprop: string; 
} 

export class MyInputField extends React.Component<MyInputFieldProps, undefined> { 
    render() { 
     return (
      <input value={this.props.myprop}/> 
     ); 
    } 
} 

是一个不好的做法,调用循环渲染方法?

THX