2016-10-24 2 views
1

Angular JS에서는 라이브 검색과 함께 제공되는 ng-repeat의 '필터'옵션을 발견했습니다. 예 :React JS의 Angular JS ng-repeat 필터 대안

<div ng-repeat="std in stdData | filter:search"> 
    <!-- 
    Std Items go here. 
    --> 
</div> 

<input type="text" placeholder="Search std items" ng-model="search.$" /> 

검색 상자에 입력 한 항목은 모두 필터링됩니다. 나는 React JS에서 이것을위한 어떤 다른 기능이 있는지 알고 싶다.

+0

무거운 각도의 배경에서 나온 ReactJS는 Angular와 같은 본격적인 프레임 워크가 아니라 확실히 라이브러리라는 것을 알게되었습니다. 당신이 당연한 일로 코드를 작성해야 할 때가있을 것입니다. 이것은 분명히 나쁜 것이 아닙니다. 그냥 관찰. 어쨌든, 나는 이것을 수행하기 위해 npm에 케이크가 있다고 확신합니다. 영감을 얻기 위해 https://react.rocks/tag/Filter를 확인하십시오. –

+0

John F. React와 100 % 일치하는 것은 모 놀리 식 프레임 워크가 아닌 사용자 영역 라이브러리입니다. 환상적으로 한 가지를하고 부팅 할 수있는 놀라운 커뮤니티가 있습니다. – Urasquirrel

답변

3

React의 해결책은 없습니다.

하지만 자신 만의 검색 창을 만들 수 있습니다. 다음 예제를 참조하십시오.

스 니펫은 주석으로 잘 처리됩니다. 이것은 당신을 도울 것입니다.

class Search extends React.Component{ 
 
    constructor(props){ 
 
    super(props) 
 
    this.state = { 
 
     items: ['car', 'mango', 'stackoverflow', 'computer'], //declare the items to be listed 
 
     searchTerm: null //initial search term will be null 
 
    } 
 
    this.onChange = this.onChange.bind(this) 
 
    } 
 
    onChange(e){ 
 
    this.setState({ 
 
     searchTerm: e.target.value //set the new serah term to the state 
 
    }) 
 
    } 
 
    render(){ 
 
    const items = this.state.items.map((item)=>{ 
 
     if(!this.state.searchTerm) return <div>{item}</div> //return the items without filter when searchterm is empty 
 
     const regEx = new RegExp(this.state.searchTerm, 'g') //create regex based on search term to filter the items 
 
     return regEx.test(item) && <div>{item}</div> //if the item passes the regex text, return that item 
 
    }) 
 
    
 
    return <div> 
 
     <input type="text" onChange={this.onChange} placeholder='search'/> 
 
     <div> 
 
     {items} 
 
     </div> 
 
    </div> 
 
    } 
 
} 
 

 
ReactDOM.render(<Search/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="app"></div>

+0

감사합니다 Pranesh Ravi. –

+0

필터를 추가하고 {items}을 (를) 변경해야하는 경우 어떻게해야합니까? 예 : filterItemsByDate byName 등? –

0

나는 반응 겨에서 이동하는 과정에서 자신이 너무 여러 번 요청했습니다, 이것은 (키를 구문 분석하는 lodash를 사용하여 값 쌍)의 해결책이 최대 끝난 날 위해 최선의 노력 : 당신이 예멘 아랍 공화국 응용 프로그램 구조의 어딘가에 해당 파일이 있으면

import _ from 'lodash'; 

function escapeRegexCharacters(str) { 
    //make sure our term won't cause the regex to evaluate it partially 
    return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); 
} 

var filterHelper = { 
    filterObjectArrayByTerm: function(arr, term) { 
    //make sure the term doesn't make regex not do what we want 
    const escapedTerm = escapeRegexCharacters(term.trim()); 
    //make the regex do what we want 
    const regEx = new RegExp (escapedTerm, 'ig'); 

    //if the term is blank or has no value, return the object array unfiltered 
    if(escapedTerm === '' || escapedTerm === null || escapedTerm === undefined) { 
    return arr; 
    } 

    //iterate over each object in the array and create a map 
    return arr.map((obj) => { 
    //if any value in a key:value pair matches the term regex 
    if(Object.values(obj).filter((value) => regEx.test(value)).length > 0){ 
     //return the object in the map 
     return obj; 
    } else { 
     //otherwise put the object in as null so it doesn't display 
     return null; 
    } 
    }); 
    }, 

//most similar to ng-repeat:ng-filter in ng 
filterObjectArrayByKeyThenTerm: function(arr, key, term) { 
    //make sure the terms don't make regex not do what we want 
    const escapedKey = escapeRegexCharacters(key.trim()); 
    const escapedTerm = escapeRegexCharacters(term.trim()); 
//make the regex do what we want 
const keyRegex = new RegExp (escapedKey, 'ig'); 
const termRegex = new RegExp (escapedTerm, 'ig'); 


    //if the key or term value is blank or has no value, return array 
    if(escapedTerm === '' || escapedTerm === null || escapedTerm === undefined || escapedKey === '' || escapedKey === null || escapedKey === undefined) { 
     return arr; 
     } 

//iterate over each object in the aray passed in and create a map 
return arr.map((obj) => { 
    //mapped object hasn't matched the regex yet 
    let match = false; 
    //can't .map() over key:value pairs, so _.each 
    _.each(obj, (value, key) => { 
    //if the key and value match the regex 
    if(keyRegex.test(key) && termRegex.test(value)) { 
     //set match to true 
     match = true; 
    } 
    }); 
    //if match was set to true 
    if(match){ 
    //return the object in the map 
    console.log('success'); 
    return obj; 
    } else { 
    //otherwise put the object in as null so it doesn't display 
    return null; 
    } 
    }); 
}, 
}; 


module.exports = filterHelper; 

, 당신은 이러한 기능 중 하나를 사용할 수 있습니다

를 호출하여
import 'filterHelper' from '/path/to/filterHelper/filterhelper.js' 

다른 구성 요소에서 ng-repeat : ng-filter in 을 사용하면 원하는 값 또는 키 : 값 쌍으로 개체 배열을 필터링 할 수 있습니다.

작업 예제 (용어, 키 및 상태 값, 기타 등으로 설정된 arr)가 마음에 드시면 알려 주시기 바랍니다.